Math.clz32()

The Math.clz32() function returns the number of leading zero bits in the 32-bit binary representation of a number.

Syntax

Math.clz32(x)

Parameters

x
A number.

Description

"clz32" is short for CountLeadingZeroes32.

If x is not a number, then it will be converted to a number first, then converted to a 32-bit unsigned integer.

If the converted 32-bit unsigned integer is 0, then return 32, because all bits are 0.

This function is particularly useful for systems that compile to JS, like Emscripten.

Examples

Using Math.clz32()

Math.clz32(1);                // 31
Math.clz32(1000);             // 22
Math.clz32();                 // 32

[NaN, Infinity, -Infinity, 0, -0, null, undefined, 'foo', {}, []].filter(
function(n) {
  return Math.clz32(n) !== 32
});                           // []

Math.clz32(true);             // 31
Math.clz32(3.5);              // 30

Polyfill

This polyfill depends on Math.imul.

Math.clz32 = Math.clz32 || (function () {
  'use strict';

  var table = [
    32, 31,  0, 16,  0, 30,  3,  0, 15,  0,  0,  0, 29, 10,  2,  0,
     0,  0, 12, 14, 21,  0, 19,  0,  0, 28,  0, 25,  0,  9,  1,  0,
    17,  0,  4,   ,  0,  0, 11,  0, 13, 22, 20,  0, 26,  0,  0, 18,
     5,  0,  0, 23,  0, 27,  0,  6,  0, 24,  7,  0,  8,  0,  0,  0]

  // Adapted from an algorithm in Hacker's Delight, page 103.
  return function (x) {
    // Note that the variables may not necessarily be the same.

    // 1. Let n = ToUint32(x).
    var v = Number(x) >>> 0

    // 2. Let p be the number of leading zero bits in the 32-bit binary representation of n.
    v |= v >>> 1
    v |= v >>> 2
    v |= v >>> 4
    v |= v >>> 8
    v |= v >>> 16
    v = table[Math.imul(v, 0x06EB14F9) >>> 26]

    // Return p.
    return v
  }
})();

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Math.clz32' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Math.clz32' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 38 31 (31) No support 25 No support
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support No support No support 31.0 (31) No support No support No support

See also

Document Tags and Contributors

 Contributors to this page: stevemao, fscholz, impinball, Mingun, realityking, evilpie, ziyunfei, Havvy
 Last updated by: stevemao,