Bad Shift Amount
ID |
java.bad_shift_amount |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports shift operations (<<, >>, >>>) where the right-hand side is a literal integer greater than 31. In Java, shift amounts are masked: amount & 0x1F for int (32 bits) and amount & 0x3F for long (64 bits). Shifting by 32 is equivalent to shifting by 0, which is almost certainly a bug.
Rationale
Java silently masks the shift amount to the width of the type. For example, 1 << 32 produces 1 (not 0), and 1 << 33 produces 2. This is rarely the intended behavior and indicates a logic error.
// Bad - equivalent to 1 << 0, which is 1
int x = 1 << 32;
// Bad - equivalent to 1 << 8, which is 256
int y = 1 << 40;
Remediation
Use a shift amount within the type width (0-31 for int, 0-63 for long). If you need more bits, use long or BigInteger.
// Good - shift within int range
int x = 1 << 16;
// Good - use long for larger shifts
long y = 1L << 40;