bitwise check if flag present
Asked Answered
D

1

30

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?

Donald answered 19/10, 2011 at 2:5 Comment(2)
You don't need the ==flagtocheckfor part. The result of the & is either 0 (bit was off) or non-0 (bit was on), and in C at least, that already corresponds to False and True.Utrillo
@librik, that's okay for single-bit masks but some may be multibit. See my answer.Pueblo
P
53

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;
Pueblo answered 19/10, 2011 at 2:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.