开发者

How to snprintf gracefully?

How to gracefully use snprintf function or some another functio开发者_StackOverflown from standard C library to fill the memory by ASCII representation of an array of unsigned char?

char data[16];
char dataRepresentation[33];
...
for (i = 0; i < 16; ++i)
        snprintf(&dataRepresentation[i * 2], 3, "%02x", (unsigned char) data[i])

Is it the easiest way to get the ASCII representation?


A bit of bit-twiddling will go much faster:

char data[16];
char dataRepresentation[2 * sizeof data];
static const char master[] = "01234567890abcdef";
...
for (i = 0; i < sizeof data; ++i)
{
     dataRepresentation[i * 2] = master[0xF&(data[i]>>4)];
     dataRepresentation[i * 2 + 1] = master[data[i]&0xF];
}

Beware that I haven't actually compiled this code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜