Get Num Leading Zeros (32bit int) in JavaScript

Posted by yhuang
Public (Editable by Users)
JavaScript
None
Edit
// 00000000000000000000000000000001
console.log(Math.clz32(1));
// expected output: 31

// 00000000000000000000000000000100
console.log(Math.clz32(4));
// expected output: 29

// 00000000000000000000001111101000
console.log(Math.clz32(1000));
// expected output: 22

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

var stuff = [NaN, Infinity, -Infinity, 0, -0, null, undefined, 'foo', {}, []];
stuff.every(n => Math.clz32(n) == 32);  // true

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