Reputation: 150108
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
int.MinValue
by these constants yield int.MinValue
(2 cases) or 0
(2 cases)?int.MinValue
indicate a flaw in the hash algorithm?Upvotes: 1
Views: 176
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