How do I generate a hashcode from a byte array in C#?

前端 未结 11 1573
故里飘歌
故里飘歌 2020-11-27 14:21

Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I\'ve used the cryptographic hash functions for this in the pa

11条回答
  •  隐瞒了意图╮
    2020-11-27 14:47

    Borrowing from the code generated by JetBrains software, I have settled on this function:

        public override int GetHashCode()
        {
            unchecked
            {
                var result = 0;
                foreach (byte b in _key)
                    result = (result*31) ^ b;
                return result;
            }
        }
    

    The problem with just XOring the bytes is that 3/4 (3 bytes) of the returned value has only 2 possible values (all on or all off). This spreads the bits around a little more.

    Setting a breakpoint in Equals was a good suggestion. Adding about 200,000 entries of my data to a Dictionary, sees about 10 Equals calls (or 1/20,000).

提交回复
热议问题