Here is your message:
Encoding and decoding is a common programming task, mostly because the computer makes the process easy. All you need to do is decide how to encode the information and write that program. Then you hope that your encoding can be decoded, so you write that program as well. The result is that you can encode something and then decode it to return the original data.
Before getting into the details, be aware that encoding isn’t the same thing as encryption. Though the encoded data may look cryptic, it’s not intended as a way to secure data. Encoding is traditionally used to represent data in a printable format, one that’s easily transmissible between different systems, or for other reasons I can’t think of right now.
The encoding task for this month’s Exercise works like this:
- Translate a character (or byte) into its two-digit hexadecimal value.
- Translate the next character into a two-digit hex value minus the first character’s value.
- Repeat Step 2 until all the data is processed.
For example, the string
"ABC" is encoded as follows:
'A' becomes 41, hexadecimal 0x41 or the character code for the letter A uppercase.
The next character,
'B', hex code 42, is encoded as 01 because 42-41 is 1.
The next character,
'C' is encoded as 01 because 42 (hex for ‘C’) minus 41 (hex for ‘B’) is 01.
This process continues for the entire string, coding the current character’s value as the difference between its own ASCII code and the previous character’s code value.
The final encoding of
"ABC" is: 410101
Here’s a sample run of my solution:
The encode program is a filter. I type Hello, world! and the output is
481D070003BDF457F803FAF8BDE9. The first value is 0x48, character ‘H’. Then comes 0x1D, which is the difference between letters ‘e’ and ‘H’. And so on.
The filter’s goal is to pipe the output string into a decoder (which will be January’s Exercise, spoiler alert) so that the original string is recovered:
Your task for this month’s Exercise is to write the encoding filter. Process input, translating each character input into a hex value for output, but based on the difference between the current character and the previous character.
Remember that the first character of the string is output as its own hex value. Above, you see the “H” in Hello output as hex 48, its own ASCII code.
Please try this Exercise on your own before checking out my solution. The task isn’t that difficult if you’re written a filter before. Well, not accounting for the math part.