javascript 位掩码:如何确定是否只设置了一位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15951776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bitmask: how to determine if only one bit is set
提问by Tim
If I have a basic bitmask...
如果我有一个基本的位掩码...
cat = 0x1;
dog = 0x2;
chicken = 0x4;
cow = 0x8;
// OMD has a chicken and a cow
onTheFarm = 0x12;
...how can I check if only one animal (i.e. one bit) is set?
...如何检查是否只设置了一只动物(即一位)?
The value of onTheFarm
must be 2n, but how can I check that programmatically (preferably in Javascript)?
的值onTheFarm
必须是 2 n,但如何以编程方式(最好在 Javascript 中)检查它?
采纳答案by Ted Hopp
You can count the number of bits that are set in a non-negative integer value with this code (adapted to JavaScript from this answer):
您可以使用此代码计算在非负整数值中设置的位数(根据此答案改编为 JavaScript ):
function countSetBits(i)
{
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
It should be much more efficient than examining each bit individually. However, it doesn't work if the sign bit is set in i
.
它应该比单独检查每个位更有效。但是,如果符号位设置在i
.
EDIT (all credit to Pointy's comment):
编辑(全部归功于 Pointy 的评论):
function isPowerOfTwo(i) {
return i > 0 && (i & (i-1)) === 0;
}
回答by Pointy
You have to check bit by bit, with a function more or less like this:
你必须一点一点地检查,使用一个或多或少这样的函数:
function p2(n) {
if (n === 0) return false;
while (n) {
if (n & 1 && n !== 1) return false;
n >>= 1;
}
return true;
}
Some CPU instruction sets have included a "count set bits" operation (the ancient CDC Cyber series was one). It's useful for some data structures implemented as bit collections. If you've got a set implemented as a string of integers, with bit positions corresponding to elements of the set data type, then getting the cardinality involves counting bits.
一些 CPU 指令集包含“计数设置位”操作(古老的 CDC Cyber 系列就是其中之一)。它对于一些实现为位集合的数据结构很有用。如果您将集合实现为一串整数,其位位置对应于集合数据类型的元素,则获取基数涉及对位进行计数。
editwow looking into Ted Hopp's answer I stumbled across this:
编辑哇看着泰德霍普的回答我偶然发现了这个:
function p2(n) {
return n !== 0 && (n & (n - 1)) === 0;
}
That's from this awesome collection of "tricks". Things like this problem are good reasons to study number theory :-)
那是来自这个很棒的“技巧”集合。像这个问题是学习数论的好理由:-)
回答by cmptrgeekken
If you're looking to see if only a single bit is set, you could take advantage of logarithms, as follows:
如果您想查看是否只设置了一位,您可以利用logarithms,如下所示:
var singleAnimal = (Math.log(onTheFarm) / Math.log(2)) % 1 == 0;
Math.log(y) / Math.log(2)
finds the x
in 2^x = y
and the x % 1
tells us if x
is a whole number. x
will only be a whole number if a single bit is set, and thus, only one animal is selected.
Math.log(y) / Math.log(2)
找到x
in2^x = y
并x % 1
告诉我们 ifx
是一个整数。x
如果设置了一位,则只会是一个整数,因此,只会选择一只动物。