I have to create a hash function based on 3 shorts. What is the best way to go about doing this?
Edit
I have an object called Point. It is composed of three shorts (x, y, z). In order to use this object within a QSet, I have to fill in the body of the following function
uint qHash(const Point &point) {
// return something here that is a unique combination of x, y, z so that
// it is very quick to calculate and has minimal (if any) hash collisions
}
That depends a great deal on what you need from the hash function.
Is speed critical?
Is a near-perfect hash distribution critical?
How large must your hash key be? 32-bits? 64-bits? Larger?
Without knowledge of any other specifics, you may want to consider something along these lines:
That will be fast and should have a reasonable distribution of bits, even if the input values for the shorts are not well distributed
UPDATE:
Modified code sample to type
uint. My variant should work well if input is in the range 0 to 512.If you’re interested in understanding why I multiply each input by a power of 31, see
Why does Java's hashCode() in String use 31 as a multiplier?