Double.GetHashCode算法或覆盖

ali*_*hoo 2 c# algorithm double gethashcode

我有一个应用程序项目,管理和非托管代码都运行,我需要使用相同的算法在两个系统中散列双值.所以要么我将覆盖System.Double.GetHashCode()或在c ++代码中使用其算法.我找不到double.gethashcode算法并决定覆盖该函数.但我有一个奇怪的错误.

无法将类型double隐式转换为System.Double

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
  public struct Double
  {
    unsafe public override int GetHashCode()
    {
      fixed (Double* dd = &this)
      {
        int* xx = (int*)dd;
        return xx[0] ^ xx[1] ;
      }

    }
  }
}

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      double dd = 123.3444; // line 1
      // Double dd = 123.3444; // line 2
      // Cannot implicitly convert type double to System.Double
      Console.WriteLine(dd.GetHashCode());

      Console.ReadLine();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我取消注释第2行我得到不能隐式转换类型double到System.Double错误.如果我运行第1行然后没有错误发生,但重写代码永远不会工作.

也许这是我尝试的非常糟糕的事情.所以任何人都知道double.gethashcode算法,所以我可以编写等效的c ++代码来获得精确的int值?

Kir*_*oll 9

这就是我所看到的Double.GetHashCode():

//The hashcode for a double is the absolute value of the integer representation
//of that double.
// 
[System.Security.SecuritySafeCritical]  // auto-generated
public unsafe override int GetHashCode() { 
    double d = m_value; 
    if (d == 0) {
        // Ensure that 0 and -0 have the same hash code 
        return 0;
    }
    long value = *(long*)(&d);
    return unchecked((int)value) ^ ((int)(value >> 32)); 
}
Run Code Online (Sandbox Code Playgroud)

  • @leppie,你是否错过了OP问题的一部分,他问道,"也许这是我尝试的非常糟糕的事情.所以任何人都知道double.gethashcode算法,所以我可以编写等效的c ++代码来获得完全的int值?" (2认同)
  • 这适用于当前的实现,但您应该谨慎依赖于实现细节,因为它们可能会发生变化.在架构之间共享哈希代码时,最好使用独立于任一平台的算法.您当然可以使用与当前实现相同的算法,但您应该模仿它,而不是使用内置方法. (2认同)

lep*_*pie 5

public struct Double
Run Code Online (Sandbox Code Playgroud)

这是第一个问题.您无法重新定义预定义类型(除非......).