Creating a Good Hash Code (GetHashCode) for BitArray

I need to create a quick hash code in GetHashCode for BitArray. I have a dictionary in which the key is BitArrays and all bitarraves are the same length.

Does anyone know a quick way to generate a good hash from a variable number of bits, as in this case?

UPDATE:

Initially, the approach I used was to access the internal array of ints directly through reflection (speed in this case is more important than encapsulation), and then XOR these values. The XOR approach seems to work well, i.e. My method "Equals" is not called excessively when searching in a dictionary:

    public int GetHashCode(BitArray array)
    {
        int hash = 0;
        foreach (int value in array.GetInternalValues())
        {
            hash ^= value;
        }
        return hash;
    }

, StackOverflow, (16570 Equals calls 16608 XOR ). , , , , -. , - .

    public int GetHashCode(BitArray array)
    {
        UInt32 hash = 17;
        int bitsRemaining = array.Length;
        foreach (int value in array.GetInternalValues())
        {
            UInt32 cleanValue = (UInt32)value;
            if (bitsRemaining < 32)
            {
                //clear any bits that are beyond the end of the array
                int bitsToWipe = 32 - bitsRemaining;
                cleanValue <<= bitsToWipe;
                cleanValue >>= bitsToWipe;
            }

            hash = hash * 23 + cleanValue;
            bitsRemaining -= 32;
        }
        return (int)hash;
    }

GetInternalValues ​​ :

public static class BitArrayExtensions
{
    static FieldInfo _internalArrayGetter = GetInternalArrayGetter();

    static FieldInfo GetInternalArrayGetter()
    {
        return typeof(BitArray).GetField("m_array", BindingFlags.NonPublic | BindingFlags.Instance);
    }

    static int[] GetInternalArray(BitArray array)
    {
        return (int[])_internalArrayGetter.GetValue(array);
    }

    public static IEnumerable<int> GetInternalValues(this BitArray array)
    {
        return GetInternalArray(array);
    }

... more extension methods
}

!

+5
2

- 32 , 32- ( ).

, 32- XOR : , " Java".

public int GetHashCode()
{
    int hash = 17;
    hash = hash * 23 + field1.GetHashCode();
    hash = hash * 23 + field2.GetHashCode();
    hash = hash * 23 + field3.GetHashCode();
    return hash;
}

. 1, 2 32 , 32 ..

+1

, . GetHashCode() CopyTo() []. , .

, , BitVector32. GetHashCode(). 32 , , , .

+3

All Articles