【问题标题】:How to count 1 bits in an integer in JavaScript如何在 JavaScript 中计算整数中的 1 位
【发布时间】:2022-02-11 17:01:55
【问题描述】:

如何计算整数中 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' 或其他非最佳方式。

【问题讨论】:

标签: javascript binary bit


【解决方案1】:

最简单的方法是使用位运算符。基本上:

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 &amp; int全为零,如果为1则等于mask。

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

【讨论】:

  • 嗯,它给了我 0。
  • @LancePollard 这只计算从位置 1 到 7 的总位数。如果你在 226 (11100010) 上尝试,你会得到 4,如果你在 225 (11100001) 上尝试,你会得到 3 . 如果你只想要开始的 0,这是行不通的
  • @sbrass 注意到,感谢您的检查。然而,像这样的方法更接近理想,使用位操作的东西。我需要了解那些遮蔽的东西是如何工作的。
  • @LancePollard 我在下面添加了另一个答案,使用位操作应该可以满足您的需要
【解决方案2】:

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

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;
}

【讨论】:

  • 第一行idx 很棘手,不确定Math.log2(num) 部分在做什么。
  • 本质上是检查二进制数的长度。例如,log2(224) 是 7.8。这意味着您需要 8 位来表示它。所以就像 2^7 是 128 而 2^8 是 256。8 是你可以用来表示 224 的最小位数。
【解决方案3】:
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

【讨论】:

    【解决方案4】:

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

    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
    }
    

    【讨论】:

    • 我更愿意使用一些小技巧:) 谢谢!
    • 处理 101 怎么样,在这种情况下,它出来计数 1 是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多