Checking if bit is not set

 ̄綄美尐妖づ 提交于 2019-11-30 03:12:21

问题


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?

I tried with if(!value & 4) or if(~value & 4) and if(value ^ 4) but none of them works.


回答1:


When you write if(value & 4), C checks the result to be non-zero. Essentially, it means

if((value & 4) != 0) {
    ...
}

Therefore, if you would like to check that the bit is not set, compare the result for equality to zero:

if((value & 4) == 0) {
    ...
}



回答2:


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



回答3:


Simply:

if ((value & 4) == 0)

Why?

If value is 01110011

Then

01110011
&
00000100
--------

Will return 0 because 4th bit is off.




回答4:


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.

The line from 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;
}


来源:https://stackoverflow.com/questions/27235738/checking-if-bit-is-not-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!