Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed Length numeric hash code from variable length string in c#

Tags:

c#

.net-3.5

hash

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.

like image 424
Kishore A Avatar asked Feb 13 '09 23:02

Kishore A


2 Answers

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);
}
like image 95
ShuggyCoUk Avatar answered Sep 22 '22 18:09

ShuggyCoUk


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

int shorthash = "test".GetHashCode() % 100000000; // 8 zeros
if (shorthash < 0) shorthash *= -1;
like image 40
Zach Scrivena Avatar answered Sep 21 '22 18:09

Zach Scrivena