Converting Hex to ASCII

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
K.J.

Converting Hex to ASCII

Post 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.
Tim

Re:Converting Hex to ASCII

Post 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
Kernel Panic

Re:Converting Hex to ASCII

Post 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;
}
Post Reply