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?
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?
>>
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:
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
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
It's a bit-shift operator. See here.
>>
performs arithmetic right shift.
For example:
12 >> 1 = 6
-12 >> 1 = -6
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