位掩码:如何确定是否只设置了一个位 [英] Bitmask: how to determine if only one bit is set

查看:104
本文介绍了位掩码:如何确定是否只设置了一个位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个基本的位掩码......

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?

onTheFarm 的值必须是2 n ,但如何以编程方式检查(最好用Javascript)?

The value of onTheFarm must be 2n, but how can I check that programmatically (preferably in Javascript)?

推荐答案

您可以使用此代码计算在非负整数值中设置的位数(改编自此JavaScript回答):

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):

function countSetBits(i)
{
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

它应该比单独检查每个位更有效。但是,如果在 i 中设置了符号位,则它不起作用。

It should be much more efficient than examining each bit individually. However, it doesn't work if the sign bit is set in i.

编辑(所有信用到Pointy的评论):

EDIT (all credit to Pointy's comment):

function isPowerOfTwo(i) {
    return i > 0 && (i & (i-1)) === 0;
}

这篇关于位掩码:如何确定是否只设置了一个位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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