簡體   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