Shift Operators in Java


References

Quiz

                          // 31                  15                 0
final int i = -1;         //  1111 1111 1111 1111 1111 1111 1111 1111

final int a = (i >>>  1); //  0111 1111 1111 1111 1111 1111 1111 1111
final int b = (i >>> 15); //  0000 0000 0000 0001 1111 1111 1111 1111
final int c = (i >>> 17); //  0000 0000 0000 0000 0111 1111 1111 1111
final int d = (i >>> 31); //  0000 0000 0000 0000 0000 0000 0000 0001

final int e = (i >>> 32); //  ???? ???? ???? ???? ???? ???? ???? ????
assert e == 0; // @@?

Answer

Here is a quote from The Java® Language Specification, Java SE 8 Edition.

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 (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Here are actual values of each right operands evaluated in above code.

decimal hexadecimal binary & 0b11111
 1 0x01 0000 0000 0000 0000 0000 0000 000 0 0001 0b00001 (0x01)
15 0x0F 0000 0000 0000 0000 0000 0000 000 0 1111 0b01111 (0x0F)
17 0x11 0000 0000 0000 0000 0000 0000 000 1 0001 0b10001 (0x11)
31 0x1F 0000 0000 0000 0000 0000 0000 000 1 1111 0b11111 (0x1F)
32 0x20 0000 0000 0000 0000 0000 0000 001 0 0000 0b00000 (0x00)

Do it for yourself

$ cat ShiftTest.java
public class ShiftTest {
    public static void main(final String[] args) {
        System.out.printf("%+d\n", -1 >>> 31);
        System.out.printf("%+d\n", -1 >>> 32);
    }
}
$ javac ShiftTest.java
$ java ShiftTest
+1
-1
$
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s