Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned right Shift '>>>' Operator in Java [duplicate]

Tags:

java

bit-shift

Possible Duplicate:
Why is (-1 >>> 32) = -1?

The unsigned right shift operator inserts a 0 in the leftmost. So when I do

System.out.println(Integer.toBinaryString(-1>>>30)) 

output

11 

Hence, it is inserting 0 in the left most bit.

System.out.println(Integer.toBinaryString(-1>>>32)) 

output

11111111111111111111111111111111 

Shouldn't it be 0?

like image 827
Keen Sage Avatar asked Jan 24 '13 12:01

Keen Sage


People also ask

Does Java support unsigned right shift?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.

What is unsigned right shift operator in Java?

The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.

What is the difference between right shift and unsigned right shift in Java?

That's all about difference between right shift and unsigned right shift operators in Java. Right shift ">>" keeps the sign extension while shifting bit patterns, but right shift without sign doesn't keep the original sign bit intact, it fills with zero.

How do you fix a right shift operator?

Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. In other words right shifting an integer “x” with an integer “y” denoted as '(x>>y)' is equivalent to dividing x with 2^y.


1 Answers

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

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.

that is -1 >>> 32 is equivalent to -1 >>> 0 and -1 >>> 33 is equivalent to -1 >>> 1 and, especially confusing, -1 >>> -1 is equivalent to -1 >>> 31

like image 58
Evgeniy Dorofeev Avatar answered Sep 22 '22 12:09

Evgeniy Dorofeev