Description
Shifting a small integer type by its bit width or more follows Go's shift and integer-conversion rules, but may produce a result different from the intended calculation. The impact depends on how the result is used in masks, sizes or other arithmetic.
Potential impact
- Incorrect masks, flags or size calculations may cause unintended behavior.
- Constant calculations may be overlooked during code review.
Remediation
- Check both the shift count and the bit width of the left operand.
- Convert to a larger integer type first when needed, and validate the input and result ranges.
Examples
Before
go
value := int32(n) << 40
After
go
value := int64(n) << 40
Explanation:
- Before: Shifting a 32-bit integer by 32 bits or more can differ from the intended 64-bit calculation.
- After: Converting to
int64first performs the 40-bit shift in the larger type. The input and final result must still fit that type.