I have a hash table whose keys are 64 bit values. The Table size can be of different lengths of power 2, such as 2, 4, 8 etc... I want a hash table function that works well for such cases, that is, it has minimum collisions. As an example, If I want a table size of 32, the hash function should produce values from 0 to 31 with minimum collision for 64 bit inputs.
I have found good solutions for 32 bit inputs but none for 64 bits inputs yet.
For 32 bit keys, I'm using this function
#define hash32(x) ( (x) * 2654435761 )
unsigned int getHashKey( unsigned long x )
{
return hash32(x) >> ( 32 - h_bits );
}
Would to be interesting to have the hash32(x) equivalent of 64 bit.
Any non- null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.
The hash function requires both key and the value. The key contains the logic that determines what index the value will live at within the underlying data structure (array or object).
A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
The search for a perfect hash function is like the search for the Holy Grail. Anyway it depends on the value.
If you need a general-purpose hashing functions on x86, Murmur2, Meiyan, SBox, and CRC32 provide good performance for all kinds of keys. For 64bit values you can also try CityHash .
This page (and this) has a few hash functions suitable for integers. Here's one for 64 bit integers:
public long hash64shift(long key)
{
key = (~key) + (key << 21); // key = (key << 21) - key - 1;
key = key ^ (key >>> 24);
key = (key + (key << 3)) + (key << 8); // key * 265
key = key ^ (key >>> 14);
key = (key + (key << 2)) + (key << 4); // key * 21
key = key ^ (key >>> 28);
key = key + (key << 31);
return key;
}
This seems to be working pretty fine. It uses the FVN hash constant for 64 bit, http://isthe.com/chongo/tech/comp/fnv/.
#define hash64(x) ( (unsigned long)(x) * 14695981039346656037 )
#define H_BITS 4 // Hashtable size = 2 ^ 4 = 16
#define H_SHIFT_64 ( 64 - H_BITS )
unsigned int getHashKey( unsigned long x )
{
return hash64(x) >> H_SHIFT_64;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With