且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有效地计算JavaScript中整数的位数

更新时间:2022-01-13 05:26:24

您可以使用 Bit Twiddling Hacks

function bitCount (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(0xFF)) //=> 8

请注意,上述策略仅适用于32位整数(JavaScript中按位运算符的限制)。

Note that the above strategy only works for 32-bit integers (a limitation of bitwise operators in JavaScript).

对于较大整数的更通用方法将涉及单独计算32位块(感谢 harold 的灵感来源:

A more general approach for larger integers would involve counting 32-bit chunks individually (thanks to harold for the inspiration):

function bitCount (n) {
  var bits = 0
  while (n !== 0) {
    bits += bitCount32(n | 0)
    n /= 0x100000000
  }
  return bits
}

function bitCount32 (n) {
  n = n - ((n >> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
  return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}

console.log(bitCount(Math.pow(2, 53) - 1)) //=> 53

你也可以使用正则表达式:

You could also use a regular expression:

function bitCount (n) {
  return n.toString(2).match(/1/g).length
}

console.log(bitCount(0xFF)) //=> 8