patrick
patrick

Reputation: 1042

How to convert Hex to Ascii in C with and without using sprintf?

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.

Upvotes: 3

Views: 19027

Answers (3)

please delete me
please delete me

Reputation:

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.

Upvotes: 10

tomlogic
tomlogic

Reputation: 11694

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

Upvotes: 0

Gabriel Ščerbák
Gabriel Ščerbák

Reputation: 18570

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

Upvotes: 1

Related Questions