Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift Operator in Java [duplicate]

Tags:

java

bit-shift

How does the shift operator << work when the value of the shift bits is greater than the total number of bits for the datatype?

For example,

int i = 2; 
int j = i<<34;
System.out.println(j);

The size of an integer is 32 bits, however we are shifting 34 bits. How does this work?

like image 608
anakin Avatar asked Nov 11 '13 05:11

anakin


2 Answers

I'm not sure the source on this, but according to WikiPedia (emphasis mine):

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 & with the mask value 0x1f (0b11111).[4] The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Edit: It looks like the WikiPedia entry basically lifted the information straight out of the Java Specification.

like image 153
mellamokb Avatar answered Oct 04 '22 07:10

mellamokb


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.

Getting back to your original problem, (i << 33) == (i << (33 & 0x1f)) == (i << 1). You can do the whole thing in binary if you like. 270 in binary is : 0000 0000 0000 0000 0000 0001 0000 1110 Shifting right by 1, you get: 0000 0000 0000 0000 0000 0000 1000 0111 which is 135.

But a better way to do this problem in your head is to dispense with the binary entirely. The value of i >> s is floor(i / 2<sup>s</sup>) (where s has already been masked off so it's less than 32). So, 270 << 1 = floor(270/2) = 135.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19

like image 26
AJ. Avatar answered Oct 04 '22 08:10

AJ.