C#实现FNV哈希

时间:2012-12-20 14:35:00

标签: c# .net hash fnv

我遇到过很多情况需要在C#中访问一个体面的哈希算法,从覆盖GetHashCode到对数据进行快速比较/查找。

我发现FNV哈希是一个非常简单/好/快的哈希算法。但是,我从未见过一个C#实现的好例子。

FNV-1a哈希算法的核心如下:

 hash = OFFSET_BASIS
 foreach (object value in object) 
 {
     hash = hash ^ value.GetHashCode()
     hash = hash * FNV_PRIME
 }

所以,当我为一个类重写GetHashCode时,我最终做了类似的事情:

public static class FNVConstants
{
    public static readonly int OffsetBasis = unchecked((int)2166136261);
    public static readonly int Prime = 16777619;
}

public override int GetHashCode()
{
    int hash = Constants.FNVConstants.OffsetBasis;
    hash = (hash ^ EntityId.GetHashCode()) * Constants.FNVConstants.Prime;
    hash = (hash ^ FromDate.GetHashCode()) * Constants.FNVConstants.Prime;
    hash = (hash ^ ToDate.GetHashCode()) * Constants.FNVConstants.Prime;
    return hash;
}

人们怎么想这个?

1 个答案:

答案 0 :(得分:7)

您可以将其添加到FNVConstants班级

public static int CreateHash(params object[] objs)
{
    return objs.Aggregate(OffsetBasis, (r, o) => (r ^ o.GetHashCode()) * Prime);
}

然后将其称为

public override int GetHashCode()
{
    return FNVConstants.CreateHash(EntityId, FromDate, ToDate);
}