开发者

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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜