哈希函数给我非常大的数字
Hash Function giving me extremely large numbers
我正在为 c 使用 djb2 哈希函数,当我通过它 运行 一个名字时,我得到了数十万个哈希值,我希望能够将它放在一个hash table 使用几千或至少在 long 中更小的数组。我很困惑如何让函数给我更小的哈希值,同时仍然具有哈希值的完整性。此外,我对如何确定用于我的散列 table 的数组的适当大小感到困惑。提前谢谢你。
unsigned long hash(char* str)
{
unsigned long hash = 5381;
int c;
for (int i = 0; i < strlen(str); ++i)
{
c = (int) str[i];
hash = ((hash << 5) + hash) + c;
}
return hash;
}
假设您的 djb2
return 版本是 unsigned long
(调用 return 变量 foo
),取其模数结果模 n
使用表达式
foo % n
将限制 0
到 n - 1
的结果。这应该与原始哈希值具有相似的理想统计特性,并且应该优于通过整数除法获得的结果。
我正在为 c 使用 djb2 哈希函数,当我通过它 运行 一个名字时,我得到了数十万个哈希值,我希望能够将它放在一个hash table 使用几千或至少在 long 中更小的数组。我很困惑如何让函数给我更小的哈希值,同时仍然具有哈希值的完整性。此外,我对如何确定用于我的散列 table 的数组的适当大小感到困惑。提前谢谢你。
unsigned long hash(char* str)
{
unsigned long hash = 5381;
int c;
for (int i = 0; i < strlen(str); ++i)
{
c = (int) str[i];
hash = ((hash << 5) + hash) + c;
}
return hash;
}
假设您的 djb2
return 版本是 unsigned long
(调用 return 变量 foo
),取其模数结果模 n
使用表达式
foo % n
将限制 0
到 n - 1
的结果。这应该与原始哈希值具有相似的理想统计特性,并且应该优于通过整数除法获得的结果。