What does ">>" mean in java
>> signed right shift operator. This shifts the sample slightly to the right. The bit combination is specified by the left operand, and the number of positions for the offset is specified by the right operand.
When you shift 2 bits to the right, you drop the 2 least significant bits.
x = 00111011 , x = 00111011
So when you do, x >> 2 , this leads to x = 00001110
In fact, this is the same as dividing the value by 4 or 2 two times when discarding the fractional part.
So the code below will result in 4
byte val = 100; val = (byte) (val >> 2); System.out.println(val); Explaining your example:
- Binary representation 12: 1100
- 12 >> 1 is equivalent to 0110, which is 6 in decimal
- therefore (12 >> 1) - 1) is equivalent to 6-1, i.e. 5
See Bitwise and Bit Shift Operators
The Java programming language also provides operators that perform bitwise and bitwise operations on integral types. A signed shift operator
<<shifts the bit to the left, and a signed right shift operator>>shifts the bit to the right. The pattern bit is specified by the left operand, and the number of positions to move along the right operand. The unsigned shift operator>>>shifts the zero to the leftmost position, and the leftmost position after>>depends on the expansion of the sign.
(12 >> 1) - 1) >> shifts binary 12(1100) 1 time to the right.12 >> 1 == 6(110)
6 - 1 == 5
Binary operator change the right side. The value of the left operands moves to the right by the number of bits specified by the right operand. For example, A → 2 will give 15, which is 1111.
Additional information: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html