Checking if a bit is set

If I use this: if(value & 4) to check if a bit is set, then how to check if a bit is set?

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

+5
source share
4 answers

When you write if(value & 4) , C checks that the result is nonzero. In essence, this means

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

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

 if((value & 4) == 0) { ... } 
+17
source

You could do it in different ways, but the simplest (the easiest, as in the case, requiring the least amount of thought) would simply negate the whole expression that you already have:

 if (!(value & 4)) 
+4
source

Simply:

 if ((value & 4) == 0) 

Why?

If value is 01110011

Then

 01110011 & 00000100 -------- 

Will return 0 because the 4th bit is turned off.

+3
source

the hastebin line is poorly written, has unreachable code, and is highly dependent on the priority of the C statements. And it does not work properly.

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; } 
0
source

Source: https://habr.com/ru/post/1208073/


All Articles