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

前端 未结 11 1598
故里飘歌
故里飘歌 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:38

    private int? hashCode;
    
    public override int GetHashCode()
    {
        if (!hashCode.HasValue)
        {
            var hash = 0;
            for (var i = 0; i < bytes.Length; i++)
            {
                hash = (hash << 4) + bytes[i];
            }
            hashCode = hash;
        }
        return hashCode.Value;
    }
    

提交回复
热议问题