【问题标题】:How to retrieve source code of String.GetHashcode() for 64 bits application?如何检索 64 位应用程序的 String.GetHashcode() 的源代码?
【发布时间】:2019-01-25 09:39:36
【问题描述】:

我犯了一个错误,将String.GetHashCode() 用于稳定,因此我通过组合 32 位 String.GetHashCode() 构建了一些“独特”的 128 位哈希。而且,确实在 MSDN 文档中,我不应该将这种方法用于稳定,因为我在 32 位应用程序上没有相同的哈希值。

我无法回滚,因为我所有的数据都写有这个错误。

在这一点上不要对我大喊大叫。

现在,我需要在 64 位平台中恢复 GetHashCode() 的实际实现,以稳定我的代码。

有什么地方可以找到吗?

这个 64 位实现应该返回(我使用 .NET 4.7.0)

  "a".GetHashCode() == 372029373; // Should be true

【问题讨论】:

  • GetHashCode()中的哈希码是.Net的私事;他们可以从版本到版本,平台到平台等。使用Sha128创建一个stable哈希码。
  • 正如我所说,我无法更改哈希系统,因为我需要更新所有数据会花费太多时间
  • @Rahul:谢谢
  • @DmitryBychenko - 阅读问题。那艘船已经航行了。

标签: c# hashcode


【解决方案1】:

对于那些犯了同样错误的人,我已经根据评论员的文档构建了这个实现。它是以下特性的默认实现:

  • .NET 4 - 4.7.2
  • 64 位
  • 发布模式

public static class StringHashExtensions
{
    public static unsafe int GetHashCode64BitsRelease(this string str)
    {
        unsafe
        {
            fixed (char* src = str)
            {
                int hash1 = 5381;
                int hash2 = hash1;

                int c;
                char* s = src;
                while ((c = s[0]) != 0)
                {
                    hash1 = ((hash1 << 5) + hash1) ^ c;
                    c = s[1];
                    if (c == 0)
                        break;
                    hash2 = ((hash2 << 5) + hash2) ^ c;
                    s += 2;
                }

                return hash1 + (hash2 * 1566083941);
            }
        }
    }
 }

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 2022-12-18
    • 2015-04-11
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多