ArrayComparer.cs

Byte Array Comparer Class

Updated: Dec-22,2020
Updated: May-04,2021

using System;
using System.Collections.Generic;
[Serializable]
public class ArrayComparer : IEqualityComparer<byte[]>
{
    private const ulong M = 0x10000000;
    public bool Equals(byte[] x, byte[] y)
    {
        if (x == null || y == null)
            return false;
        if (x.Length != y.Length)
            return false;
        return x.Compare(y);
    }
    public unsafe int GetHashCode(byte[] obj)
    {
        var cbSize = obj.Length;
        var hash   = 0x811C9DC5;
        fixed (byte* pb = obj)
        {
            var nb = pb;
            while (cbSize >= 4)
            {
                hash   ^= *(uint*) nb;
                hash   *= 0x1000193;
                hash   %= 0x10000000;
                nb     += 4;
                cbSize -= 4;
            }
            switch (cbSize & 3)
            {
                case 3:
                    hash ^= *(uint*) (nb + 2);
                    hash *= 0x1000193;
                    hash %= 0x10000000;
                    goto case 2;
                case 2:
                    hash ^= *(uint*) (nb + 1);
                    hash *= 0x1000193;
                    hash %= 0x10000000;
                    goto case 1;
                case 1:
                    hash ^= *nb;
                    hash *= 0x1000193;
                    hash %= 0x10000000;
                    break;
            }
        }
        return (int) hash;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *