整数类型转换并获取C#中的哈希代码

本文关键字:哈希 代码 类型转换 获取 整数 | 更新日期: 2023-09-27 18:01:45

In.Net:

Int16 d1 = n;
Int32 d2 = (Int32)d1;

确实d1.GetHashCode()等于d2.GetHashCode()对于任何16位整数n

Int32Int64,以及UInt16Int32是否也存在同样的关系?这种关系会适用于所有整数转换吗?

整数类型转换并获取C#中的哈希代码

不,没有,你可以用一个简单的程序来检查一下。

float d1 = 0.5f;
double d2 = (double)d1;
Console.WriteLine(d1.GetHashCode());
Console.WriteLine(d2.GetHashCode());

返回

1056964608
1071644672

来自微软源代码页floatGetHashCode

public unsafe override int GetHashCode() 
{
    float f = m_value;
    if (f == 0) {
        // Ensure that 0 and -0 have the same hash code
        return 0;
    }
    int v = *(int*)(&f);
    return v;
}

对于double:

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));
}

正如你所看到的,答案是:没有

此外,一个小程序也可以告诉你这一点。

来自Frank J 发布的同一源代码页

我现在知道答案是否定的,我应该在得到我的情况的哈希码之前进行投票

UInt16.GetHashCode:

internal ushort m_value;
// Returns a HashCode for the UInt16
public override int GetHashCode() {
    return (int)m_value;
}

Int16.GetHashCode:

internal short m_value;
// Returns a HashCode for the Int16
public override int GetHashCode() {
    return ((int)((ushort)m_value) | (((int)m_value) << 16));
}

UInt32.GetHashCode:

internal uint m_value;
public override int GetHashCode() {
    return ((int) m_value);
}

Int32.GetHashCode:

internal int m_value;
public override int GetHashCode() {
    return m_value;
}

Int64.GetHashCode:

internal long m_value;
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode() {
    return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}

UInt64.GetHashCode

internal ulong m_value;
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode() {
    return ((int)m_value) ^ (int)(m_value >> 32);
}