Question

I have seen the C# function String.GetHashCode(); is used to return a 32bit integer hash of a string.

I want to generate a simple 16bit hash of a string value. The string will always be 9 characters long.

Can anyone assist?

Thanks

Était-ce utile?

La solution

Be careful using GetHashCode(). This function is only guaranteed to return same hash for given application domain. It's return value can change from platform to platform and version to version for the same string value. So if you are storing this hash value for later or sending it out, you may get surprise. Otherwise this is a faster hash function. Here's how you can use it without needing unchecked:

public static Int16 Get16BitHash(string s)
{
    return (Int16) (s.GetHashCode() & 0xFFFF);
}

If you are ok with slight performance hit then you can use MD5 hash. This hash can be stored or passed around for later use without worries. Here's how:

public static Int16 Get16BitHash2(string s)
{
    using (var md5Hasher = MD5.Create())
    {
        var data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(s));
        return BitConverter.ToInt16(data, 0);
    }
}

A word of caution: 16-bit hashses are very likely to collide if you have too many strings because of Birthday Paradox. Generally safe hash size if 128-bit.

Autres conseils

You can simply take 16 bits from string.GetHashCode by casting it to a 16-bit number (short or ushort). You'll need to include the unchecked keyword if you'd otherwise be running in a checked context.

unchecked
{
    return (short)someString.GetHashCode();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top