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

时间:2015-07-08 18:32:43

标签: c#

在.Net:

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

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

同样的关系与Int32Int64以及UInt16Int32保持一致吗?所有整数转换都会保持相同的关系吗?

3 个答案:

答案 0 :(得分:2)

不,它没有,你可以用一个简单的程序检查自己。

float d1 = 0.5f;
double d2 = (double)d1;

Console.WriteLine(d1.GetHashCode());
Console.WriteLine(d2.GetHashCode());

返回

1056964608
1071644672

答案 1 :(得分:1)

来自Microsofts Source Code Page GetHashCode的{​​{1}}:

float

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

你可以看到答案是:否

除此之外,一个小程序也可以告诉你。

答案 2 :(得分:1)

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