Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise operator >>> in hashCode

I have two related questions:

  1. the bitwise operator >>> means that we are shifting the binary number by those many places while filling 0 in the Most Significant Bit. But, then why does the following operation yields the same number: 5>>>32 yields 5 and -5>>>32 yields -5. Because if the above description is correct then both these operations would have yielded 0 as the final result.

  2. In continuation to above, As per Effective Java book, we should use (int) (f ^ (f >>> 32)) (in case the field is long) while calculating the hash code (if the field is long). Why do we do that and what's the explanation

like image 990
Gaurav Avatar asked Oct 28 '13 08:10

Gaurav


2 Answers

5 can be represented as 0101 if you shift it by 1 bit i.e 5>>>1 this will result as 0010=2

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

When you shift an integer with the << or >> operator and the shift distance is greater than or equal to 32, you take the shift distance mod 32 (in other words, you mask off all but the low order 5 bits of the shift distance). This can be very counterintuitive. For example (i> >> 32) == i, for every integer i. You might expect it to shift the entire number off to the right, returning 0 for positive inputs and -1 for negative inputs, but it doesn't; it simply returns i, because (i << (32 & 0x1f)) == (i << 0) == i.

like image 95
AJ. Avatar answered Sep 28 '22 11:09

AJ.


Answer to your first question is here why is 1>>32 == 1?

The second question answer, in short, is that in such way the whole long value is used(not a part of it) and note that it is probably the fastest way to do this.

like image 25
Andrii Andriichuk Avatar answered Sep 28 '22 11:09

Andrii Andriichuk