首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Math.clz32

Math.clz32()函数返回一个数字在转换成 32 无符号整形数字的二进制形式后, 开头的 0 的个数。

语法

代码语言:javascript
复制
Math.clz32(x)

参数

x一个数值。

返回值

给定数字的32位二进制表示中前导零位的数量。

描述

"clz32" 是 CountLeadingZeroes32的缩写.

如果?x?不是数字类型, 则它首先会被转换成数字类型, 然后再转成 32 位无符号整形数字.?

如果转换后的 32 位无符号整形数字是?0, 则返回32, 因为此时所有位上都是?0.

这个函数主要用于那些编译目标为 JS 语言的系统中, 比如 Emscripten.

示例

使用Math.clz32()

代码语言:javascript
复制
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

以下polyfill是最有效的。

代码语言:javascript
复制
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);
  };
}

规范

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

?

浏览器兼容性

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)

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com