Create a hashcode of two numbers

My normal way of creating a hashcode for an arbitrary set of hashable items:

int hash = 23;
hash = hash * 31 + item1Hash;
hash = hash * 31 + item2Hash;
hash = hash * 31 + item3Hash;
hash = hash * 31 + item4Hash;
hash = hash * 31 + item5Hash;
// etc

In your case item1Hash could just be a, and item2Hash could just be b.

The values of 23 and 31 are relatively unimportant, so long as they’re primes (or at least coprime).

Obviously there will still be collisions, but you don’t run into the normal nasty problems of:

hash(a, a) == hash(b, b)
hash(a, b) == hash(b, a)

If you know more about what the real values of a and b are likely to be you can probably do better, but this is a good initial implementation which is easy to remember and implement. Note that if there’s any chance that you’ll build the assembly with “check for arithmetic overflow/underflow” ticked, you should put it all in an unchecked block. (Overflow is fine for this algorithm.)

Leave a Comment