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
Input the hexadecimal value | The ASCII text is | |
---|---|---|
Here is how it is done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | char* hexToAscii(char hex[]) { int hexLength = strlen(hex); char* text = NULL; if(hexLength > 0) { int symbolCount; int oddHexCount = hexLength % 2 == 1; if(oddHexCount) symbolCount = (hexLength / 2) + 1; else 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]); if(oddHexCount) text[i/2+1] = dec; else text[i/2] = dec; } else if(i == 0) { int dec = valueOf(hex[0]); text[0] = dec; } } text[symbolCount] = '\n'; } return text; } |
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
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: