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?
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.
>> 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.
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.
>>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With