[英]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
位置。
mask & int
如果int的第i
位为0则全为0,如果为1则等于mask。
编辑:我在控制台上做了一些尝试。 首先,我去掉了 break,然后在 if 语句中添加了一些圆括号。 可能是数字表示的一些问题使得该陈述不可能为真。
所以这是另一个使用位旋转的任意位长度解决方案:
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
对任意位长度数字执行此操作的方法可能类似于:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.