Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise check if flag present

Is there a method typically used to check if a flag is present in an int/other data type? I figured out something like this:

if ((host&flagtocheckfor)==flagtocheckfor) 

Which works fine- however it's such a common method of setting flags is this the way flags are usually checked? Or is there a more concise method?

like image 743
ultifinitus Avatar asked Oct 19 '11 02:10

ultifinitus


People also ask

How do I find a Bitwise flag?

To check a flag state, we use bitwise AND operator (&). It allows to determine if bit is on or off.

How do you know if a flag is set?

FLAG – Check if flag is set This function checks if binary flags are set within a byte, but performed in decimal number form, to avoid having to convert values to binary. The function returns 1 if the bits in <check> are also set in <source> . On the contrary, it returns 0.


1 Answers

That's pretty well exactly the way bit flags are checked in most languages that support them.

For example:

#define BIT_7 0x80 #define BITS_0_AND_1 0x03  if ((flag & BIT_7) == BIT_7) ... if ((flag & BITS_0_AND_1) == BITS_0_AND_1) ... 

While you can check something like the first with:

if ((flag & BIT_7) != 0) ... 

that won't actually work for the second since it will return true if either of the bits are set, not both.

For completeness, C allows you to set the bit masks with:

flag = flag | BIT_7;   // or you can also use 'flag |= BIT_7' 

You can clear them with:

flag = flag & (~BIT_7); 

And toggle them with:

flag = flag ^ BIT_7; 
like image 158
paxdiablo Avatar answered Sep 20 '22 23:09

paxdiablo