How to convert from ASCII to Hex and vice versa? [closed]
I need to convert ASCII
to HEX
and HEX
to A开发者_高级运维SCII
by using a C program.
Here's a simplistic function to convert one character to a hexadecimal string.
char hexDigit(unsigned n)
{
if (n < 10) {
return n + '0';
} else {
return (n - 10) + 'A';
}
}
void charToHex(char c, char hex[3])
{
hex[0] = hexDigit(c / 0x10);
hex[1] = hexDigit(c % 0x10);
hex[2] = '\0';
}
Its pretty easy. Scan through character by character ... best to start from the end. If the character is a number between 0 and 9 or a letter between a and f then place it in the correct position by left shifting it by the number of digits you've found so far.
For converting to a string then you do similar but first you mask and right shift the values. You then convert them to the character and place them in the string.
精彩评论