如何在 C# 中实现 sdbm 哈希函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 08:51:53  来源:igfitidea点击:

How would a sdbm hash function be implemented in C#?

提问by Christo

How can a sdbmhash function (such as this) be implemented in C# ?

如何在 C# 中实现sdbm散列函数(例如这个)?

回答by Timbo

You can take the C code almost without changes:

您几乎无需更改即可使用 C 代码:

uint sdbm( string str )
{
    uint hash = 0;
    foreach( char ch in str )
    {
        hash = ch + (hash << 6) + (hash << 16) - hash;
    }
    return hash;
}

Or did you think of something more sophisticated?

或者你有没有想到更复杂的东西?

回答by ICR

I don't have a C compiler set up so I can't test to see if it performs the same, but I thinkthe following is correct:

我没有设置 C 编译器,所以我无法测试它是否执行相同的操作,但我认为以下内容是正确的:

private static ulong SBDM(string str)
{
    ulong hash = 0;

    foreach (char c in str)
    {
        hash = c + (hash << 6) + (hash << 16) - hash;
    }

    return hash;
}

If you just need to get a hash of the string and it doesn't matter too much what the implementation is you can always do the String.GetHashCode();

如果您只需要获取字符串的哈希值并且实现方式无关紧要,您可以随时执行String.GetHashCode();

回答by Christo

The result from the hash differs between the C++ and C# implementation. I figured out that str parameter needs to be passed as a byte array.

散列的结果在 C++ 和 C# 实现之间有所不同。我发现 str 参数需要作为字节数组传递。

private uint sdbm(byte[] str)
{
    uint hash = 0;

    foreach (char ch in str)
        hash = ch + (hash << 6) + (hash << 16) - hash;

    return hash;
}

Call the method by converting the value to be hashed with the BitConverter.GetBytesmethod.

通过转换要使用该BitConverter.GetBytes方法散列的值来调用该方法。

uint Hash = sdbm(BitConverter.GetBytes(myID));