How would a sdbm hash function be implemented in C

2019-07-01 15:31发布

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

标签: c# hash
3条回答
一纸荒年 Trace。
2楼-- · 2019-07-01 15:48

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));
查看更多
爷的心禁止访问
3楼-- · 2019-07-01 15:50

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 theString.GetHashCode();

查看更多
我命由我不由天
4楼-- · 2019-07-01 16:02

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?

查看更多
登录 后发表回答