Search code examples
c++-cligethashcode

GetHashCode - Generate hash code from 64-bit address


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

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?


Solution

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

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

    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.