gpt4 book ai didi

FNV哈希的C#实现

转载 作者:太空狗 更新时间:2023-10-29 18:35:56 33 4
gpt4 key购买 nike

在很多情况下,我需要在 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;
}

人们对此有何看法?

最佳答案

您可以将其添加到您的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);
}

关于FNV哈希的C#实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974443/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com