Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Bit operations >>> shift

Why if

int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31; 

we have 00000000000000000000000000000001

but if

int x = -1
x = x >>> 32;

we have 11111111111111111111111111111111 (again -1)

but not 00000000000000000000000000000000 ?

like image 203
ses Avatar asked Feb 11 '13 17:02

ses


People also ask

What is this >>> Bitwise operator in Java?

In Java, bitwise operators perform operations on integer data at the individual bit-level. Here, the integer data includes byte , short , int , and long types of data. There are 7 operators to perform bit-level operations in Java.

What is the use of >>> operator?

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0 , so the result is always non-negative.

What is the difference between >> and >>> in Java?

Difference between >> and >>> operator. Both >> and >>> are used to shift the bits towards the right. The difference is that the >> preserve the sign bit while the operator >>> does not preserve the sign bit. To preserve the sign bit, you need to add 0 in the MSB.

Can you do bit shifting in Java?

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.


1 Answers

From Section 15.19 of JLS:

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.

Emphasis mine. So:

x >>> n

is equivalent to:

x >>> n & 0x1f  // or x >>> n % 32

So, x >>> 32 is equivalent to x >>> 32 & 0x1f <==> x >>> 0 == x.

So the Rule of Thumb is, whenever you shift a number by a multiple of 32(int is 32 bits), you get back the same value.

like image 113
Rohit Jain Avatar answered Oct 30 '22 14:10

Rohit Jain