48

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bad Dub
  • 1,503
  • 2
  • 22
  • 52

6 Answers6

57

>> 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kartic
  • 2,935
  • 5
  • 22
  • 43
36

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
CSCH
  • 621
  • 6
  • 15
4

See Bitwise and Bit Shift Operators

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The signed left shift operator << shifts a bit pattern to the left, and the signed right shift operator >> 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. The unsigned right shift operator >>> shifts a zero into the leftmost position, while the leftmost position after >> depends on sign extension.

(12 >> 1) - 1)         

>> shifts binary 12(1100) 1 times to the right.
12 >> 1 == 6(110)

6 - 1 == 5

2

It's a bit-shift operator. See here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pathfinderelite
  • 3,047
  • 1
  • 27
  • 30
2

>> performs arithmetic right shift.

For example:

12 >> 1 = 6
-12 >> 1 = -6
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
botismarius
  • 2,977
  • 2
  • 30
  • 29
1

Binary right shift operator. The left operand's value is moved right by the number of bits specified by the right operand. For example, A >> 2 will give 15 which is 1111 in binary.

More information: Bitwise and Bit Shift Operators

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cristiam Mercado
  • 573
  • 12
  • 34