Hex to ASCII text
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
Here is how it is done:
- Starting from the right-most hex symbol, group the hex input in pairs of 2.
For example 68657821 will be 68 65 78 21
This means that the left-most group could contain only 1 symbol (if the input has an odd number of hexadecimal digits)
- (Optional) Convert each group to its decimal representation. If in 3. you use a table that has the hex mappings, then you don't need this step.
For example 21hex = 33dec
- Replace each number with its corresponding symbol from the ASCII table.
Continuing the example above:
68hex = 104dec = h
65hex = 101dec = e
78hex = 120dec = x
21hex = 33dec = !
68657821 = hex!
Hex to ASCII conversion in C
char* hexToAscii(char hex)
int hexLength = strlen(hex);
char* text = NULL;
if(hexLength > 0)
int oddHexCount = hexLength % 2 == 1;
symbolCount = (hexLength / 2) + 1;
symbolCount = hexLength / 2;
text = malloc(symbolCount + 1);
int lastIndex = hexLength - 1;
for(int i = lastIndex; i >= 0; --i)
if(((lastIndex - i) % 2 != 0))
int dec = 16 * valueOf(hex[i]) + valueOf(hex[i+1]);
text[i/2+1] = dec;
text[i/2] = dec;
else if(i == 0)
int dec = valueOf(hex);
text = dec;
text[symbolCount] = '\n';
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: