Using Bitwise and in If statements...

Status
Not open for further replies.

BLMinTenn

Well-known member
All,
A quick question for the group. I am using a byte as 8 booleans and in some of my "IF" statements, I am reading certain bits to be "true" per the example below.
Code:
if(bit_bool & (1<<0)) {do_something();}

In the instance where you would want to check if the bit boolean is false condition, would you write as such...
Code:
if(!(bit_bool & (1<<0)))  {do_nothing();}

or would the code below have to be substituted...
Code:
if(bit_bool & (1<<0) != true) {do_nothing();}

I am currently not at a computer to test this so, please forgive that aspect.

Thanks
Bryan
 
I think it is better not to think of these as boolean quantities because they aren't. Treat them as individual bit "flags" in a byte. If you want to test if bit N is set, test whether it is non-zero:
Code:
if(bit_bool & (1<<N))  {do_nothing();}
or if you want to a bit more explicit about it:
Code:
if((bit_bool & (1<<N)) != 0) {do_nothing();}

To test if it is zero use this:
Code:
if((bit_bool & (1<<N)) == 0) {do_nothing();}

Pete
 
Status
Not open for further replies.
Back
Top