La funci贸 Math.clz32()
retorna el nombre de zeros a l'esquerra que apareixen en una representaci贸 bin脿ria de 32 bits per a un nombre.
Sintaxi
Math.clz32(x)
Par脿metres
x
- Un nombre.
Descripci贸
"clz32
" 茅s una abreviaci贸 de CountLeadingZeroes32
.
Si x
no 茅s un nombre, primer es convertir脿 a un nombre, i despr茅s es convertir脿 a un nombre sencer de 32 bits sense signe.
Si el nombre sencer sense signe de 32 bits 茅s 0
, la funci贸 retornar脿 32
ja que tots els bits s贸n 0
.
Aquesta funci贸 茅s particulament 煤til per a sistemes que compilin en JavaScript, com ara Emscripten.
Exemples
Utilitzar 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
Aquesta funci贸 polyfill utilitza 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]
// Adaptat d'un algorisme trobat a Hacker's Delight, p脿gina 103.
return function (x) {
// Tingueu en compte que les variables no tenen perqu猫 ser les mateixes.
// 1. On n = ToUint32(x).
var v = Number(x) >>> 0
// 2. On p 茅s el nombre de zeros a l'esquerra en la representaci贸 bin脿ria de 32 bits de n.
v |= v >>> 1
v |= v >>> 2
v |= v >>> 4
v |= v >>> 8
v |= v >>> 16
v = table[Math.imul(v, 0x06EB14F9) >>> 26]
// Retorna p.
return v
}
})();
Especificacions
Especificaci贸 | Estat | Comentaris |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.clz32' in that specification. |
Standard | Definici贸 inicial. |
Compatibilitat amb navegadors
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Caracter铆stica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Suport b脿sic | 38 | 31 (31) | No support | 25 | No support |
Caracter铆stica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Suport b脿sic | No support | No support | 31.0 (31) | No support | No support | No support |