GetHashCode-从64位地址生成哈希码 [英] GetHashCode - Generate hash code from 64-bit address

查看:69
本文介绍了GetHashCode-从64位地址生成哈希码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个32位C ++ / CLI程序集,其中一个类包装了一个本机对象。它覆盖GetHashCode以返回它包装的本机对象的地址(m_native是指针):

We've got a 32-bit C++/CLI assembly and one of the classes wraps a native object. It overrides GetHashCode to return the address of the native object it wraps (m_native is a pointer):

int NativeWrapper::GetHashCode()
{
    return (int)m_native;
}

我现在正在将该程序集转换为支持64位,因此当前GetHashCode实现不再适合。是否有合适的算法可以从64位地址生成哈希码?还是我想念一个更简单的选择?

I'm now converting this assembly to support 64-bit, so the current GetHashCode implementation is no longer suitable. Are there any suitable algorithms to generate a hash code from a 64-bit address? Or am I missing an easier alternative?

推荐答案

我将使用与.Net框架相同的算法来生成 Int64的哈希码:低32位与高32位进行异或

I would use the same algorithm as the .Net framework does for generating the hash code of an Int64: the lower 32 bits XORed with the upper 32 bits.

int NativeWrapper::GetHashCode()
{
    return ((int)m_native) ^ (int)(m_native >> 32);
}

尽管如此,您可以为简单的截断提供理由:这就是 IntPtr.GetHashCode 可以。

Although, you could make a case for simple truncation: That's what IntPtr.GetHashCode does.

如果要支持双32/64编译,则可以将 m_native 强制转换为 IntPtr 并使用其GetHashCode是一个很好的实现,可以在32位和64位模式下工作。

If you want to support a dual 32/64 compile, perhaps casting m_native to IntPtr and using its GetHashCode would be a good implementation that works in both 32 and 64 bit modes.

这篇关于GetHashCode-从64位地址生成哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆