Using Bitwise operators on flags

Malfist picture Malfist · Feb 9, 2009 · Viewed 30.3k times · Source

I have four flags

Current = 0x1  
Past = 0x2  
Future = 0x4  
All = 0x7

Say I receive the two flags Past and Future (setFlags(PAST | FUTURE)). How can I tell if Past is in it? Likewise how can I tell that Current is not in it? That way I don't have to test for every possible combination.

Answer

Marc Gravell picture Marc Gravell · Feb 9, 2009

If you want all bits in the test mask to match:

if((value & mask) == mask) {...}

If you want any single bit in the test mask to match:

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

The difference is most apparent when you are testing a value for multiple things.

To test for exclusion:

if ((value & mask) == 0) { }