Eric J.
Eric J.

Reputation: 150108

Creating Hash Code and Overflow

I am trying to generate a hash code from two integer inputs. The approach outlined in

Combining Java hashcodes into a "master" hashcode

seems to work well for many input values. However, when one of the input integers is int.MinValue, the behavior seems less than ideal. Specifically I observe

int.MinValue * 1013 == int.MinValue

int.MinValue * 1009 == int.MinValue

but

int.MinValue * 2 == 0

int.MinValue * 20 == 0

All of this is in an unchecked context.

I would naively (and wrongly) assume that int.MinValue * (something other than 1 or 0) would yield a new bit pattern different than int.MinValue or 0.

Questions

  1. Why does multiplying int.MinValue by these constants yield int.MinValue (2 cases) or 0 (2 cases)?
  2. Does the behavior of int.MinValue indicate a flaw in the hash algorithm?

Upvotes: 1

Views: 176

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100537

Multiplication is more or lest shift of bits to left. Since int.MinValue is 0x80000000 (only one highest bit set) multiplication can produce only two int values - 0 (if multiplying by even number ) or value with highest bit still set (for odd numbers).

Sample for 4 bit numbers (x,y,z - any value for particular bit, 1000 is equivalent of int.MinValue )

1000 * xyz1 =
   (xyz0 * 1000)  + 1000 * 1 = 
   (xyz  * 10000) + 1000 * 1 =  
   (xyz  * 0)     + 1000 = 1000

1000 * xyz0 = 
   (xyz  * 10000) + 1000 * 0 =  0

Upvotes: 2

Related Questions