开发者

SHA1 hash binary (20) to string (41)

I have a function that creates a binary sha1, but I need a result as a 40-byte string, (+1 for null-t). Is there a better way of conver开发者_StackOverflow中文版ting it to string, than this?

unsigned char hash_binary[20] = "\xFF\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01";
char hash_string[41];
int i;

for(i = 0;i < 20; i++)
    sprintf( hash_string + i*2, "%02X", hash_binary[i] );

hash_string[40] = 0;

This calls sprintf 20 times. How can I avoid it?


You can populate the target string directly:

static const char alphabet[] = "0123456789ABCDEF";

for (int i = 0; i != 20; ++i)
{
  hash_string[2*i]     = alphabet[hash_binary[i] / 16];
  hash_string[2*i + 1] = alphabet[hash_binary[i] % 16];
}
hash_string[40] = '\0';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜