将MD5结果转换为C中的整数 [英] Converting MD5 result into an integer in C
问题描述
我的目标是使用MD5结果的结果来索引哈希表.我想对其执行模数运算,以在表中找到合适的插槽.我尝试将其强制转换为无符号的long long类型.当我打印结果时,对于相同的MD5哈希,每次都会得到一个不同的数字. MD5哈希最初是一个无符号的char *.有人可以告诉我我在做什么错吗?
My goal is to use the result of an MD5 result to index a hash table. I want to perform a Modulo operation on it to find the appropriate slot in the table. I have tried casting it as an unsigned long long type. When I printed the result, I got a different number every time for the same MD5 hash. The MD5 hash is initially an unsigned char *. Can someone tell me what I am doing wrong?
这是我的功能:
int get_fp_slot(unsigned char * fingerprint, int size)
{
return (unsigned long long)fingerprint % size;
}
推荐答案
MD5哈希是一个128位数字.因此,为了获得最佳性能,您可能应该保留所有128位.
An MD5 hash is a 128 bit number. So for best performance you should probably keep all 128 bits.
鉴于您的函数将128位哈希作为字符串,因此您需要将该字符串解析为4个整数的序列.您的字符串可能看起来像这样:
Given that your function takes the 128 bit hash as a character string, you need to parse that string into a series of 4 integers. Your string probably looks something like this:
79054025255fb1a26e4bc422aef54eb4
这是一个32字节的十六进制字符串.如果是这样,您可以像这样提取二进制版本:
That is a 32 byte hexadecimal string. If so, you extract the binary version like this:
int v1, v2, v3, v4;
sscanf( &fingerprint[0], "%x", &v1 );
sscanf( &fingerprint[8], "%x", &v2 );
sscanf( &fingerprint[16], "%x", &v3 );
sscanf( &fingerprint[24], "%x", &v4 );
您现在要做的事情实际上取决于您希望哈希值有多好.如果您确实需要使用32位数字,则只需对所有这些数字进行XOR:
What you do now really depends on how good you want your hash to be. If you really need to use a 32 bit number then just XOR all those numbers together:
int hash = v1 ^ v2 ^ v3 ^v4;
这篇关于将MD5结果转换为C中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!