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.
Return value
The number of leading zero bits in the 32-bit binary representation of the given 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
The following polyfill is the most efficient.
if (!Math.clz32) { Math.clz32 = function(x) { // Let n be ToUint32(x). // Let p be the number of leading zero bits in // the 32-bit binary representation of n. // Return p. if (x == null || x === 0) { return 32; } return 31 - Math.floor(Math.log(x >>> 0) * Math.LOG2E); }; }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.clz32' in that specification. |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Math.clz32' in that specification. |
Draft |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Feature | Chrome | Firefox | Edge | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic Support | 38 | 31 | (Yes) | (No) | 25 | (Yes) |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | 31 | (No) | (Yes) | (Yes) |