Fixed Length numeric hash code from variable lengt

2020-02-26 06:23发布

问题:

I need to store fixed-length (up to 8 digits) numbers produced from a variable length strings. The hash need not be unique. It just needs to change when input string changes. Is there a hash function in .Net that does this?

Thanks
Kishore.

回答1:

I assume you are doing this because you need to store the value elsewhere and compare against it. Thus Zach's answer (while entirely correct) may cause you issues since the contract for String.GetHashCode() is explicit about its scope for changing.

Thus here is a fixed and easily repeatable in other languages version.

I assume you will know at compile time the number of decimal digits available. This is based on the Jenkins One At a Time Hash (as implemented and exhaustively tested by Bret Mulvey), as such it has excellent avalanching behaviour (a change of one bit in the input propagates to all bits of the output) which means the somewhat lazy modulo reduction in bits at the end is not a serious flaw for most uses (though you could do better with more complex behaviour)

const int MUST_BE_LESS_THAN = 100000000; // 8 decimal digits

public int GetStableHash(string s)
{
    uint hash = 0;
    // if you care this can be done much faster with unsafe 
    // using fixed char* reinterpreted as a byte*
    foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
    {   
        hash += b;
        hash += (hash << 10);
        hash ^= (hash >> 6);    
    }
    // final avalanche
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    // helpfully we only want positive integer < MUST_BE_LESS_THAN
    // so simple truncate cast is ok if not perfect
    return (int)(hash % MUST_BE_LESS_THAN);
}


回答2:

Simple approach (note that this is platform-dependent):

int shorthash = "test".GetHashCode() % 100000000; // 8 zeros
if (shorthash < 0) shorthash *= -1;


回答3:

Use System.Security.Cryptography.MD5CryptoServiceProvider.ComputeHash to get a MD5 hash, truncate it to the desired length.



标签: c# .net-3.5 hash