Out-of-range bit shift

Out-of-range bit shift

Description

JavaScript shifts Number values as 32-bit integers and uses only the low five bits of the shift count.

Potential impact

A negative count or one above 31 can test the wrong permission bit or produce an incorrect size or index.

Remediation

Limit Number shift counts to integers from 0 through 31. For wider integer operations, use BigInt. Test constants used in masks or size calculations against the intended result.

Examples

Before

javascript
const ADMIN_MASK = 1 << 32;

function hasAdmin(flags) {
  return (flags & ADMIN_MASK) !== 0;
}

After

javascript
const ADMIN_MASK = 1n << 32n;

function hasAdmin(flags) {
  return (BigInt(flags) & ADMIN_MASK) !== 0n;
}

1 << 32 equals 1. The BigInt expression 1n << 32n sets the intended 33rd bit. For a large value of flags, pass an exact integer string or a BigInt and check its format and range. Converting to Number first can lose precision.

References