繁体   English   中英

Double.GetHashCode算法或覆盖

[英]Double.GetHashCode algorithm or override

我有一个应用程序项目,管理和非托管代码都运行,我需要使用相同的算法在两个系统中散列双值。 所以要么我将覆盖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();
    }
  }
}

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

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

这是我在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)); 
}
public struct Double

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

您的自定义双重类型有两个问题:

  • 它不包含任何数据。
  • 它不会转换为double和from。

第一个是通过在结构中简单地使用double类型的私有变量来解决的。

第二个是通过使用隐式转换器来解决的。

public struct CustomDouble {

  private double _value;

  public override int GetHashCode() {
    byte[] data = BitConverter.GetBytes(_value);
    int x = BitConverter.ToInt32(data, 0);
    int y = BitConverter.ToInt32(data, 4);
    return x ^ y;
  }

  public static implicit operator double(CustomDouble d) {
    return d._value;
  }

  public static implicit operator CustomDouble(double d) {
    return new CustomDouble() { _value = d };
  }

}

例:

// Use the conversion from double to CustomDouble
CustomDouble d = 3.14;

// Use the CustomDouble.GetHashCode method:
Console.WriteLine(d.GetHashCode()); // 300063655

// Use the conversion from CustomDouble to double:
Console.WriteLine(d); // 3.14

使用扩展方法,Luke。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM