如何计算 JavaScript 中整数中的 1 位

How to count 1 bits in an integer in JavaScript

如何计算整数中 1 的位数。

假设你有二进制数11100000。基本上开头有 3 个布尔标志。对应的十进制表示法是224。想知道如何获取该整数并以某种方式循环遍历它以添加它开头的 1 的数量。像这样:

var int = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  if (int.getBitAt(i) == 1) {
    total++
  } else {
    break
  }
}

我从来没有真正处理过位,所以不确定如何以最佳方式完成此操作(即不将其转换为字符串 '11100000' 或其他非最佳方式。

获得这种东西的最简单方法是使用按位运算符。基本上:

var num = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  var mask = 1 << i
  if ( (mask & num) == (mask)) {
    total++
  }
}

基本上mask是一个变量,一个地方是1,其他地方都是0,比如0001000,高位在i位置。

如果int的i位为0,

mask & int全为0,为1则等于mask。

编辑:我在控制台上进行了一些尝试。首先,我去掉了 break,然后在 if 语句中添加了一些圆括号。可能是数字表示的一些问题使得该陈述不可能为真。

对任意位长度数字执行此操作的方法可能类似于:

function countBits(num){
    var s=num.toString(2); //Converts the number to a binary string
    if (s[0]==='0'){return 0;} //If the first digit is 0, return 0
    return s.split('0')[0].length; //Otherwise, return the number of 1s at the start
}

所以这是另一个使用位旋转的任意位长度解决方案:

function countBits(num){
    var idx=Math.floor(Math.log2(num)); //Get the number of bits needed to represent your number
    var bit=1;
    var count=0;
    while (bit){
        bit=(num & (1<<idx))>>idx; //Check the bit value in the given position
        count+=bit; //Add it to the count
        idx-=1; //Check the next bit over
    }
    return count;
}
const num = 42726; // value to count set bits in
const numBytes = 2; // number of bytes used to represent num
let i = 0;
let count = 0;
while (i < numBytes * 8) {
  if (((1 << i) & num) >> i === 1) count++;
  i++;
}
console.log(count); // 9