Bit shifts at or beyond the integer type width

Bit shifts at or beyond the integer type width

Description

A left shift on a Go integer variable discards bits that move past the width of its type.

Potential impact

Lost bits can change a mask, flag or calculated size.

Remediation

Check the shift count and the width needed for the result. Convert to a wider type before shifting if needed, and check that both the input and the intended result fit.

Examples

Before

go
value := int32(n) << 40

After

go
value := int64(n) << 40

For a variable n, int32(n) << 40 shifts out all 32 bits and produces zero. The second expression shifts int64(n) by 40 bits.

References