Search code examples
c#.netstringhash64-bit

C# 4.0 How to get 64 bit hash code of given string


I want to get 64 bit hash code of given string. How can i do that with fastest way ? There is a ready method for get 32 bit hash code but i need 64 bit.

I am looking for only integer hashing. Not md5.

Thank you very much.

C# 4.0


Solution

  • This code is from Code Project Article - Convert String to 64bit Integer

     static Int64 GetInt64HashCode(string strText)
    {
        Int64 hashCode = 0;
        if (!string.IsNullOrEmpty(strText))
        {
            //Unicode Encode Covering all characterset
              byte[] byteContents = Encoding.Unicode.GetBytes(strText);
            System.Security.Cryptography.SHA256 hash = 
            new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] hashText = hash.ComputeHash(byteContents);
            //32Byte hashText separate
            //hashCodeStart = 0~7  8Byte
            //hashCodeMedium = 8~23  8Byte
            //hashCodeEnd = 24~31  8Byte
            //and Fold
            Int64 hashCodeStart = BitConverter.ToInt64(hashText, 0);
            Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);
            Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24);
            hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
        }
        return (hashCode);
    }