tags:

views:

132

answers:

3

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.

A: 

Check out Formatting Codes, if your C implementation supports it, it should be easy to print values in hexadecimal.

Gabriel Ščerbák
+4  A: 

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.

brone
+1 if you add `chars[2] = '\0'` (and some spaces couldn't hurt your code either.)
Chris Lutz
Updated code to make it clearer what's going on.
brone
A: 

Check your C library for ltoa -- the inverse of strtol. Or, write it from scratch (see brone's answer).

tomlogic