如何在 C# 中实现 DJBX33X 哈希函数?以下是该函数的 C 代码。
uint32_t hash(const char *arKey, uint32_t nKeyLength)
{
uint32_t hash = 5381;
for (; nKeyLength > 0; nKeyLength -=1)
{
hash = ((hash << 5) + hash) ^ *arKey++;
}
return hash;
}
已更新这是到目前为止我的代码,但 C 和 C# 函数的结果不同,我错过了什么吗?
public static long hash(string str)
{
long hash = 5381;
for (int i = 0; i < str.Length; i++)
{
hash = ((hash << 5) + hash) ^ (int)str[i];
}
return hash;
}
更新 2 以下是 C 和 C# 的输出
C#
t = 116(<<172192+177573) -> 177617
t = 116(<<5683744+5861361) -> 5861253
u = 117(<<187560096+193421349) -> 193421392
U = 85(<<6189484544+6382905936) -> 6382905861
'ttuU' => '6382905861'
C
t = 116 (<<172192+177573) -> 177617
t = 116 (<<5683744+5861361) -> 5861253
u = 117 (<<187560096+193421349) -> 193421392
U = 85 (<<1894517248+2087938640) -> 2087938565
'ttuU' -> '2087938565'
最佳答案
数据类型可能对于哈希实现很重要;您必须引用文档才能获得确切的答案,但此函数会产生您期望的结果:
public static uint Hash(string str)
{
uint result = 5381;
for (int i = 0; i < str.Length; i++)
{
result = ((result << 5) + result) ^ str[i];
}
return result;
}
示例输出:
Hash("ttuU") -> 2087938565
关于c# - C# 中的 DJBX33X 哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729567/