The shift operator in Java

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

For instance,

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

The integer size is 32 bits, however we shift 34 bits. How it works?

+6
source share
3 answers

When you shift an integer with the character <or β†’, and the shift distance is greater than or equal to 32, you take the shift distance of mod 32 (in other words, you mask everything except 5 bits of shift).

This can be very controversial. For example (i >> 32) == i , for each integer i. You can expect it to shift the entire number to the right, returning 0 for positive inputs and -1 for negative inputs, but this is not the case; it just returns i because (i << (32 & 0x1f)) == (i << 0) == i .

Returning to the original problem, (i <<33) == (i <(33 and 0x1f)) == (i <1). You can do it all in binary if you want. 270 in binary: 0000 0000 0000 0000 0000 0000 0001 0000 1110 Offset to the right by 1, you get: 0000 0000 0000 0000 0000 0000 1000 1000 0111, which is 135.

But the best way to make this problem in your head is to completely abandon binary code. The value i >> s is floor(i / 2<sup>s</sup>) (where s is already masked, so it is 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

+4
source

I'm not sure if this is the source, but according to WikiPedia (my attention):

If the advanced type of the left operand is int, only the five least significant bits of the right operand are used as a distance offset . It is as if the right operand was subjected to a bitwise logical AND operator with a mask value of 0x1f (0b11111). [4] Therefore, the actually used shear distance is always in the range from 0 to 31 inclusive.

Edit: It appears that the WikiPedia entry basically output information directly from the Java Specification .

+6
source

If you try 1 << 34 , you get 4 . Runtime basically has an implicit mod NUMBER_OF_BITS in the right shift operand. In the previous example, this is 1 << (34 % 32) , which becomes 1 << 2 , which is 4.

+1
source

Source: https://habr.com/ru/post/957806/


All Articles