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.

3 Answers 3

10

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.

1
  • 1
    +1 if you add chars[2] = '\0' (and some spaces couldn't hurt your code either.)
    – Chris Lutz
    Apr 26, 2010 at 6:06
1

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.