Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created May 8, 2018 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neuecc/6304f106f4cb66d3616c1cecb485fbd0 to your computer and use it in GitHub Desktop.
Save neuecc/6304f106f4cb66d3616c1cecb485fbd0 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
public class ByteArrayEqualityComparer : IEqualityComparer<byte[]>
{
// FNV1-1a 32bit https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
public int GetHashCode(byte[] obj)
{
uint hash = 0;
if (obj != null)
{
hash = 2166136261;
for (int i = 0; i < obj.Length; i++)
{
hash = unchecked((obj[i] ^ hash) * 16777619);
}
}
return unchecked((int)hash);
}
public bool Equals(byte[] xs, byte[] ys)
{
if (object.ReferenceEquals(xs, ys)) return true;
if (xs == null) return false;
if (ys == null) return false;
if (xs.Length != ys.Length) return false;
for (int i = 0; i < xs.Length; i++)
{
if (xs[i] != ys[i]) return false;
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
var xs = new byte[] { 1, 10, 100 };
var ys = new byte[] { 1, 10, 100 };
var zs = new byte[] { 1, 10, 150 };
var dict = new Dictionary<byte[], int>(new ByteArrayEqualityComparer());
dict.Add(xs, 0);
Console.WriteLine(dict.ContainsKey(ys)); // true;
Console.WriteLine(dict.ContainsKey(zs)); // false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment