Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ">>" symbol mean in Java? [duplicate]

Tags:

java

I see a line in some code I'm looking at and it says (12 >> 1) - 1). I print that value out and it comes out as a 5. If I change the 12 to 5, it comes out as a 1.

What is the ">>" symbol doing exactly?

like image 712
Bad Dub Avatar asked May 02 '15 16:05

Bad Dub


People also ask

What does >> in Java mean?

In Java, the operator '>>' is signed right shift operator. All integers are signed in Java, and it is fine to use >> for negative numbers. The operator '>>' uses the sign bit (leftmost bit) to fill the trailing positions after the shift.

What does >> mean code?

>> is the signed right shift operator. It shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. When you shift right two bits, you drop the two least significant bits.

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

In simple words >>> always shifts a zero into the leftmost position whereas >> shifts based on sign of the number i.e. 1 for negative number and 0 for positive number. For example try with negative as well as positive numbers.


2 Answers

>> is the signed right shift operator. It shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.

When you shift right two bits, you drop the two least significant bits.

Let’s say, x = 00111011

So when you do, x >> 2, it results in x = 00001110

This is essentially the same thing as dividing a value by 4 or by 2 two times while dropping the fractional part.

So, below code will result in 4:

byte val = 100; val = (byte) (val >> 2); System.out.println(val); 

Explaining your example:

  • The binary representation of 12 is: 1100
  • 12 >> 1 is equivalent to 0110 which is 6 in decimal
  • so (12 >> 1) - 1) is equivalent to 6-1 that is 5
like image 163
Kartic Avatar answered Sep 20 '22 14:09

Kartic


12 is 1100 in binary. A right shift (>> is the bitwise right shift operator) by one bit produces

1100 -> 0110  

which comes out to be 6.

Thus we have that,

6 - 1 = 5 
like image 44
CSCH Avatar answered Sep 19 '22 14:09

CSCH