Page 1 of 1

Converting Hex to ASCII

Posted: Sun Apr 21, 2002 1:52 pm
by K.J.
How do I convert a hex number to printable ASCII?
Like for a debugger that would display a dump of the registers.

Thanks in advance,
K.J.

Re:Converting Hex to ASCII

Posted: Sun Apr 21, 2002 3:21 pm
by Tim
Start writing at the right-hand end of your string
Do
Let digit = (number AND 0xF)
If 0 <= digit < 10 then
Write character ('0' + digit) to your string
Else
Write character ('a' + digit - 10) to your string
Move to the previous character in the string
Shift number right by 4 bits
While number is not zero

You can generalise this to any number base:

Start writing at the right-hand end of your string
Do
Let digit = (number MOD base)
If 0 <= digit < 10 then
Write character ('0' + digit) to your string
Else
Write character ('a' + digit - 10) to your string
Move to the previous character in the string
Divide number by base
While number is not zero

Re:Converting Hex to ASCII

Posted: Tue Apr 23, 2002 11:40 am
by Kernel Panic
Or, for hex, just something like this:

Code: Select all

char hex[] = "0123456789ABCDEF";
int number = 0xDEADC0DE
int i;

for (i = 0; i < 8; i++)
{
  printf("%c", hex[(number & 0xF0000000) >> 28];
  number = number << 4;
}