Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator ‘>>’ which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators.
Here we will be discussing both of right shift operators as listed:
- Signed right shift “>>”
- Unsigned right shift “>>>”
Type 1: Signed Right Shift
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. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if the binary representation of a number is 10….100, then right shifting it by 2 using >> will make it 11…….1.
Type 2: Unsigned Right Shift Operator
In Java, the operator ‘>>>’ denotes unsigned right shift operator and always fill 0 irrespective of the sign of the number.
7 3 1
Time Complexity: O(1).
Space Complexity: O(1) as no extra space has been used.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...