Left shift by more than the type width¶
ID: java/lshift-larger-than-type-width
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- correctness
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
The maximum shift distance used for left-shift operations is determined by the promoted type of its left-hand side. When the promoted type is int
only the lowest 5 bits of the right-hand side are used as the shift distance. When the promoted type is long
the lowest 6 bits of the right-hand side are used.
Recommendation¶
Restrict the amount that you shift any int
to the range 0-31, or cast it to long
before applying the left shift.
Example¶
The following line tries to left-shift an int
by 32 bits.
long longVal = intVal << 32; // BAD
However, left-shifting an int
by 32 bits is equivalent to left-shifting it by 0 bits, that is, no shift is applied. Instead the value should be cast to long
before the shift is applied. Then the left-shift of 32 bits will work.
long longVal = ((long)intVal) << 32; // GOOD
References¶
Java Language Specification: Shift Operators.