C语言 检查位是否未设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27235738/
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
Checking if bit is not set
提问by Protogrammer
If I use this:
if(value & 4)to check if the bit is set, then how do I check if the bit isn't set?
如果我使用这个:
if(value & 4)来检查该位是否已设置,那么我如何检查该位是否未设置?
I tried with
if(!value & 4)or if(~value & 4)and if(value ^ 4)but none of them works.
我尝试使用
if(!value & 4)orif(~value & 4)和if(value ^ 4)但它们都不起作用。
回答by dasblinkenlight
When you write if(value & 4), C checks the result to be non-zero. Essentially, it means
当您编写 时if(value & 4),C 检查结果是否为非零。本质上,这意味着
if((value & 4) != 0) {
...
}
Therefore, if you would like to check that the bit is notset, compare the result for equality to zero:
因此,如果您想检查该位是否未设置,请将相等的结果与零进行比较:
if((value & 4) == 0) {
...
}
回答by Kevin DiTraglia
You could do it many ways, but the easiest (easiest as in requires the least amount of thought) would be just negate the entire expression you already have:
你可以用很多方法来做,但最简单的(最简单的,需要最少的思考)就是否定你已经拥有的整个表达式:
if (!(value & 4))
回答by Maroun
Simply:
简单地:
if ((value & 4) == 0)
Why?
为什么?
If valueis 01110011
如果value是 01110011
Then
然后
01110011
&
00000100
--------
Will return 0 because 4th bit is off.
将返回 0,因为第 4 位关闭。
回答by user3629249
the line from hastebin is poorly written, has unreachable code and depends heavily on the Precedence of the C operators. And doesn't work as expected.
来自 hastebin 的行写得不好,代码无法访问,并且严重依赖于 C 运算符的优先级。并且没有按预期工作。
The line from hastebin:
来自 hastebin 的线路:
if( cur_w > source.xpos + source.width
&&
!(source.attributes & DBOX_HAS_SHADOW) )
{
break;
return;
}
it should be written as:
它应该写成:
if( (cur_w > (source.xpos + source.width)) // has curr_w exceeded sum of two other fields?
&&
((source.attributes & DBOX_HAS_SHADOW) != DBOX_HAS_SHADOW ) //is bit == 0?
{
break;
}

