Suitable hash code methods for an array of bytes?

后端 未结 4 1664

What is the best hash method for an array of byte?

The arrays are serialized class objects containing jpeg image passed between applications over TCP/IP

4条回答
  •  醉梦人生
    2021-01-18 06:30

    Based on the Compiler Generated GetHashCode()

    public static int GetHashCode(byte[] array) {
        unchecked {
            int i = 0;
            int hash = 17;
            int rounded = array.Length & ~3;
    
            hash = 31 * hash + array.Length;
    
            for (; i < rounded; i += 4) {
                hash = 31 * hash + BitConverter.ToInt32(array, i);
            }
    
            if (i < array.Length) {
                int val = array[i];
                i++;
    
                if (i < array.Length) {
                    val |= array[i] << 8;
                    i++;
    
                    if (i < array.Length) {
                        val |= array[i] << 16;
                    }
                }
    
                hash = 31 * hash + val;
            }
    
            return hash;
        }
    }
    

    Ah... and a link to C# Murmurhash http://landman-code.blogspot.com/2009/02/c-superfasthash-and-murmurhash2.html

提交回复
热议问题