des*_*old 0 c hash hex format-specifiers
我正在尝试实现一个返回十六进制值字符串的函数.我使用此函数打印出十六进制值:
void print_hex(unsigned char *hash, const hashid type) {
int i;
for (i = 0; i < mhash_get_block_size(type); i++) {
printf("%.2x", hex[i]);
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
这会输出一些十六进制值,例如 71c092a79cf30c4c7e7baf46a4af3c78cedec9ae3867d1e2600ffc39d58beaf2
如何修改此函数以使其返回字符串?即
unsigned char *get_hash_str(unsigned char *hash, const hashid type) { /* ?? */ }
Run Code Online (Sandbox Code Playgroud)
(目标是稍后比较2个值)
char * print_hex(const unsigned char *hash, const hashid type)
{
const char lookupTable[]="0123456789abcdef";
const size_t hashLength=mhash_get_block_size(type);
size_t i;
char * out=malloc(hashLength*2+1);
if(out==NULL)
return NULL;
for (i = 0; i < hashLength; i++)
{
out[i*2]=lookupTable[hash[i]>>4];
out[i*2+1]=lookupTable[hash[i]&0xf];
}
out[hashLength*2]=0;
return out;
}
Run Code Online (Sandbox Code Playgroud)
显然调用者负责free返回的字符串.
不过,正如@ K-Ballo在他的回答中正确地说的那样,你不需要将两个哈希值转换成字符串来比较它们,在这种情况下你需要的只是一个memcmp.
int compare_hashes(const unsigned char * hash1, const hashid hash1type, const unsigned char * hash2, const hashid hash2type)
{
if(hash1type!=hash2type)
return 0;
return memcmp(hash1, hash2, mhash_get_block_size(hash1type))==0;
}
Run Code Online (Sandbox Code Playgroud)