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

时光毁灭记忆、已成空白 提交于 2019-12-23 22:01:33

问题


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


回答1:


You can take the C code almost without changes:

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?




回答2:


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

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();




回答3:


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.

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.GetBytes method.

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


来源:https://stackoverflow.com/questions/15954/how-would-a-sdbm-hash-function-be-implemented-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!