Since an int
is a 32-bit variable, shifting by more than +/-31 is confusing at best and an error at worst. When the runtime shifts
32-bit integers, it uses the lowest 5 bits of the shift count operand. In other words, shifting an int
by 32 is the same as shifting it
by 0, and shifting it by 33 is the same as shifting it by 1.
Similarly, when shifting 64-bit integers, the runtime uses the lowest 6 bits of the shift count operand and shifting long
by 64 is the
same as shifting it by 0, and shifting it by 65 is the same as shifting it by 1.
Noncompliant Code Example
public int shift(int a) {
int x = a >> 32; // Noncompliant
return a << 48; // Noncompliant
}
Compliant Solution
public int shift(int a) {
int x = a >> 31;
return a << 16;
}
Exceptions
This rule doesn’t raise an issue when the shift by zero is obviously for cosmetic reasons:
- When the value shifted is a literal.
- When there is a similar shift at the same position on line before or after. E.g.:
bytes[loc+0] = (byte)(value >> 8);
bytes[loc+1] = (byte)(value >> 0);