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.
Converting Hex to ASCII
Re:Converting Hex to ASCII
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
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
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;
}