让用户传入要写入的缓冲区以及大小。显然,该函数必须重命名。即使这有点通用。也许应该是format_hash_to_hex_string()
因为hashid
参数。
int format_hex_string(unsigned char const *hash, hashid type, char *buffer, size_t buflen)
{
size_t n = mhash_get_block_size(type);
if (buflen < 2 * n + 1)
return -1;
for (size_t i = 0; i < n; i++)
sprintf(&buffer[2*i], "%.2X", hash[i]);
return 0;
}
或者,如果您相信您的用户能够提供足够大的缓冲区:
format_hex_string(unsigned char const *hash, hashid type, char *buffer)
{
size_t n = mhash_get_block_size(type);
for (size_t i = 0; i < n; i++)
sprintf(&buffer[2*i], "%.2X", hash[i]);
}
或者,如果您更喜欢旋转(这可能比调用更快sprintf()
):
int format_hex_string(unsigned char const *hash, hashid type, char *buffer, size_t buflen)
{
static char const hexdigits[] = "0123456789ABCDEF";
size_t n = mhash_get_block_size(type);
if (buflen < 2 * n + 1)
return -1;
for (size_t i = 0; i < n; i++)
{
*buffer++ = hexdigits[hash[i] >> 4];
*buffer++ = hexdigits[hash[i] & 0xF];
}
*buffer = '\0';
return 0;
}
为了证明通用名称的合理性,最好hashid type
用简单的长度替换参数(然后您可以合理地假设程序员知道缓冲区长度必须至少是哈希长度的 2 倍):
int format_hex_string(unsigned char const *binbuffer, size_t binlen, char *hexbuffer)
{
static char const hexdigits[] = "0123456789ABCDEF";
for (size_t i = 0; i < binlen; i++)
{
*hexbuffer++ = hexdigits[binbuffer[i] >> 4];
*hexbuffer++ = hexdigits[binbuffer[i] & 0xF];
}
*hexbuffer = '\0';
}
现在这是一个通用功能。如果你愿意,你可以将它包装成专门用于你的哈希格式;包装器可能会节省您编写一些对mhash_get_block_size()
函数的调用。