c# - C# 中的 DJBX33X 哈希函数

标签 c# hash

如何在 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/

相关文章:

c# - 如何从数据库中获取谷歌地图用户的位置?

c - C for 循环是否在遇到 '\0' 字符时退出?

Jquery:如果 url 包含特定哈希值,则有条件地添加类

algorithm - 散列对文本中的小变化稳定

ruby - 如何合并多个哈希?

c# - Mono.Security加载问题

c# - ASP .NET - 设置 DetailsView TextBox 的值

security - 用哈希值存储盐可以吗?

c# - 在 C# 中将字符串拆分为数组然后循环

c# - 从代码创建 Azure Redis 缓存