How to convert Hex to Ascii in C with and without using sprintf?
c
Solution
To do this manually, the easiest way is to have a table mapping nybbles to ASCII:
static const char nybble_chars[] = "0123456789ABCDEF";
Then to convert a byte into 2 hex chars -- assuming `unsigned char` is the best representation for a byte, but making no assumptions about its size -- extract each nybble and get the char for it:
void get_byte_hex( unsigned char b, char *ch1, char *ch2 ) {
*ch1 = nybble_chars[ ( b >> 4 ) & 0x0F ];
*ch2 = nybble_chars[ b & 0x0F ];
}
This extends straightforwardly to wider data types, and should generate reasonably concise code across a wide range of architectures.
Problem
I used `strtol` to convert a string to hex, now I need to print it to the screen. I'm not sure if I can use `sprintf` since I only have 20k of memory to use on this board. Alternatives welcome.