简体   繁体   English

C中的位操作和标志测试

[英]Bit manipulation and Flags testing in C

Suppose I have two variables of type int , a and b , and a flag F . 假设我有两个intab类型的变量,以及一个标志F

#define F <something>

int a = <something> ;
int b = <something> ;

What is a simple way to test that both a and b , have the flag F , or none of them has it? 什么是一种简单的方法来测试ab ,有标志F ,还是没有它有?

To test if both of them have it, I can use something like: 为了测试它们是否都有它,我可以使用类似的东西:

if ( a & b & F )

To test if none of them has it, I can use something like: 为了测试它们是否都没有,我可以使用类似的东西:

if ( !((a & F) || (b & F)) )

And the whole test becomes: 整个测试变成:

if ( (a & b & F) &&  !((a & F) || (b & F)) )

But this looks, too long and too complicated. 但这看起来太长太复杂了。 Is there any simpler solution? 有没有更简单的解决方案?

The test for "none of them has it" can be 对“没有人拥有它”的测试可以

!((a | b) & F)

Merge the flags, mask and flip the logic. 合并标志,屏蔽并翻转逻辑。


The whole test can be written using xor. 整个测试可以使用xor编写。 (Thanks to Martin James for the idea) (感谢Martin James的想法)

!((a ^ b) & F)

This means "not (exactly one of a or b has F )" 这意味着“不是( ab只有一个有F )”

You are looking for bit equality, which can be tested by applying XOR operator ^ , inverting the result, and masking. 您正在寻找位相等,可以通过应用XOR运算符^ ,反转结果和屏蔽来测试。

a ^ b sets bits to 1 only where the corresponding bits of a and b are different. a ^ b仅在ab的相应位不同的情况下将位设置为1。 For corresponding bits that are the same the result bit will be set to zero. 对于相同的相同位,结果位将被设置为零。

If you invert the result, you'd get ones in positions of equal bits: 如果你反转结果,你会得到相同位的位置:

~(a ^ b)

The only thing that remains is to mask with F , and check for equality: 唯一剩下的就是用F掩码,并检查是否相等:

if ((~(a ^ b) & F) == F) {
    ... // All bits indicated by F are set to the same value in a and b
}

也许这一个

!((a & F) ^ (b & F))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM