如何在JavaScript中计算整数中的1位 [英] How to count 1 bits in an integer in JavaScript

查看:95
本文介绍了如何在JavaScript中计算整数中的1位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算整数中1位的数目.

How to count the number of 1 bits in an integer.

所以说您有二进制数字11100000.基本上,开头有3个布尔值标志.与此对应的十进制表示法是224.想知道如何采用该整数并以某种方式遍历该整数以增加其开头的1的数目.像这样:

So say you have the binary number 11100000. Basically there are 3 boolean flags at the beginning. The corresponding decimal notation for this is 224. Wondering how to take that integer and loop through it somehow to add the number of 1s that it starts with. Something like this:

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

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

I've never really dealt with bits so not sure how to accomplish this in an optimal way (i.e. without converting it to a string '11100000' or other unoptimal ways.

推荐答案

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

The easiest way to get such a thing is using bitwise operators. Basically:

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位置.

Basically mask is a variable which is 1 at one place and 0 at all other places, like 0001000 with the high bit at i position.

mask & int都为零;如果为1,则等于mask.

mask & int is all zero if the i bit of int is 0, equal to mask if it is 1.

我在控制台上做了一些尝试.首先,我摆脱了中断,然后在if语句中添加了一些括号.数字的表示形式可能存在一些问题,使得该陈述不成立.

I gave some tries on the console. First of all I got rid of the break, then I added some parenthes in the if statement. Probably some problems with the representation for the numbers made impossible for the statement to be true.

这篇关于如何在JavaScript中计算整数中的1位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆