Math.clz32()

Math.clz32(x)
Returns: number · Added in ves6 · Updated March 16, 2026 · Math
math binary bitwise performance

The Math.clz32() function returns the number of leading zero bits in the 32-bit binary representation of a number. The name “clz32” stands for “count leading zeros 32”. This function is particularly useful in low-level programming, graphics, and performance-critical code where bit manipulation matters.

Syntax

Math.clz32(x)

Parameters

  • x — Any number. Non-numeric values are coerced to numbers.

Return Value

A number between 0 and 32 representing the count of leading zero bits in the 32-bit binary representation of the argument.

Examples

Basic usage

console.log(Math.clz32(1));
// 31

console.log(Math.clz32(0));
// 32

console.log(Math.clz32(-1));
// 0

Understanding the output

// 1 in 32-bit binary: 00000000000000000000000000000001
// 31 leading zeros
console.log(Math.clz32(1));
// 31

// 2 in 32-bit binary: 00000000000000000000000000000010
// 30 leading zeros
console.log(Math.clz32(2));
// 30

// 256 in 32-bit binary: 00000000000000000000000100000000
// 23 leading zeros
console.log(Math.clz32(256));
// 23

// 0b10000000000000000000000000000000 (highest bit set)
// 0 leading zeros
console.log(Math.clz32(2147483648));
// 0

Integer conversion

// Non-integers are converted to 32-bit integers first
console.log(Math.clz32(3.7));
// 30 (3 becomes 0b00000000000000000000000000000011)

// Negative numbers are treated as unsigned 32-bit integers
console.log(Math.clz32(-1));
// 0 (all bits are 1s in two's complement)

Common Patterns

Finding the bit position of the highest set bit

function highestBitPosition(n) {
  if (n === 0) return 0;
  return 31 - Math.clz32(n);
}

console.log(highestBitPosition(256));
// 8

console.log(highestBitPosition(1024));
// 10

console.log(highestBitPosition(1));
// 0

Checking if a number is a power of two

function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}

function clz32IsPowerOfTwo(n) {
  return n > 0 && Math.clz32(n) + Math.clz32(n - 1) === 31;
}

console.log(isPowerOfTwo(256));
// true

console.log(clz32IsPowerOfTwo(256));
// true

console.log(isPowerOfTwo(100));
// false

console.log(clz32IsPowerOfTwo(100));
// false

Fast integer division by powers of two

function divideByPowerOfTwo(n, divisor) {
  // Works only for positive divisors that are powers of 2
  const shift = Math.clz32(divisor) - 31;
  return n >> shift;
}

console.log(divideByPowerOfTwo(1024, 4));
// 256

console.log(divideByPowerOfTwo(100, 2));
// 50

See Also