I'm trying to make a hash function for int16_t
. The function prototype looks like this:
uint64_t hash_int16_t(const void *key);
So far I've gotten this but I don't know if this is the correct approach:
uint64_t hash_int16_t(const void *key)
{
// key is expected to be an int16_t
const int16_t *e = (const int16_t*)key;
uint64_t x = (uint64_t)*e;
x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb);
x = x ^ (x >> 31);
return x;
}
Is there a hash function for signed types? Should I mix the bits using 16 bit unsigned integers or 64 bit unsigned integers will do fine? Will I be loosing information when I cast it to an unsigned type if the integer is negative? Will this generate undefined behavior?
P.S. The code is in C and I've taken the hash function from here.
Edit 1: The argument is const void *key
because the user is allowed to store keys as other values like structs or strings. The above function will add support to int16_t
keys.
Edit 2: What I'm trying to accomplish is a generic hash table. The user will have to provide a hash function when initializing the hash table and the example above is bundled with the hash table.