When we say "Hex to ASCII", we refer to converting a hexadecimal code to
an ASCII encoded text. If these are new for you, take a look at our
lesson for hexadecimal numbers and ASCII table.
Now, let's make our first conversion using the online converter below. Try to enter the following: 54686973206d6573736167652077617320656e636f64656420696e2068657821
You can find the entire code of the demo on Git Hub.
The implementation in C just follows the algorithm, described above. Several key moments
- If the input contains an odd number of digits, the calculations are slightly different - that is why we add the oddHexCount variable.
- Make sure to properly combine the input digits 2 by 2 - we need to iterate the input starting from its end.
- You may need to read how the hexadecimal to decimal conversion is done.
- The hexToAscii function allocates memory using the malloc() routine. The resulting char array will be returned by the function. After you are done with it in the calling place, you need to free that memory using free(). This is also included in the complete source code in the git hub link above.
- Never forget to terminate your string using '\n' or NULL
- Note that in this implementation we don't check for the 0x prefix that is often used with hexadecimal values.
The rest of the hex to ASCII conversion is plain work with arrays, pointer arithmetic and type conversion(char to int and int to char).
And the output of the program looks like this: