signed vs unsigned right shift operators
In Java, both the >> (signed right shift) and >>> (unsigned right shift) operators are used for bitwise right shift operations on integer types. However, they differ in how they handle the sign bit when shifting.
Table of Contents
1. ‘>>’ (Signed Right Shift):
- The ‘>>’ operator shifts the bits of a number to the right by a specified number of positions.
- It preserves the sign bit (the leftmost bit) when shifting, which means that it maintains the sign of the original number.
- When performing a right shift on negative numbers, the ‘>>’ operator fills the vacant leftmost bits with the sign bit (0 for positive numbers, 1 for negative numbers), which preserves the sign of the number.
Example
int num = -8; // Binary representation: 1111 1111 1111 1000
int result = num >> 2; // Right shift by 2 positions
// After right shift: 1111 1111 1111 1111 (sign bit is preserved)
System.out.println(result); // Output: -2
2. ‘>>>’ (Unsigned Right Shift):
- The ‘>>>’ operator also shifts the bits of a number to the right by a specified number of positions.
- Unlike ‘>>’, the ‘>>>’ operator fills the vacant leftmost bits with zero regardless of the sign of the number.
- It treats the number as if it were unsigned, effectively shifting in zeros from the left.
Example
int num = -8; // Binary representation: 1111 1111 1111 1000
int result = num >>> 2; // Unsigned right shift by 2 positions
// After unsigned right shift: 0011 1111 1111 1111 (zeros are shifted in)
System.out.println(result); // Output: 1073741823
In summary, the main difference between ‘>>’ and ‘>>>’ operators in Java is how they handle the sign bit when shifting bits to the right. ‘>>’ preserves the sign bit, while ‘>>>’ fills vacant bits with zero, treating the number as if it were unsigned.