knuth multiplicative hash

后端 未结 4 872
一生所求
一生所求 2021-02-02 03:10

Is this a correct implementation of the Knuth multiplicative hash.

int hash(int v)
{
    v *= 2654435761;
    return v >> 32;
}

Does over

4条回答
  •  庸人自扰
    2021-02-02 03:42

    If the input argument is a pointer then I use this

    #include 
    
    uint32_t knuth_mul_hash(void* k) {
      ptrdiff_t v = (ptrdiff_t)k * UINT32_C(2654435761);
      v >>= ((sizeof(ptrdiff_t) - sizeof(uint32_t)) * 8); // Right-shift v by the size difference between a pointer and a 32-bit integer (0 for x86, 32 for x64)
      return (uint32_t)(v & UINT32_MAX);
    }
    

    I usually use this as the default fallback hashing function in hashmap implementations, dictionaries, sets, etc...

提交回复
热议问题