Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bitwise operators on flags

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.

like image 687
Malfist Avatar asked Feb 09 '09 21:02

Malfist


People also ask

Can you use bitwise operators on Booleans?

5.2. Bitwise OR. Along with integer operands, the bitwise OR can also be used with boolean operands. It returns true if at least one of the operands is true, otherwise, it returns false.

Can bitwise operators be applied to float or double variables?

16 : Bitwise Operators (i) Bitwise operators cannot be applied to float or double. They can be applied to integers only.

How do you use bitwise or inclusive?

The | (bitwise inclusive OR) operator compares the values (in binary format) of each operand and yields a value whose bit pattern shows which bits in either of the operands has the value 1 . If both of the bits are 0 , the result of that bit is 0 ; otherwise, the result is 1 .

What is bitwise operators used for?

A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits. Bitwise operators are used in: Communication stacks where the individual bits in the header attached to the data signify important information.


2 Answers

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) { } 
like image 116
Marc Gravell Avatar answered Oct 03 '22 00:10

Marc Gravell


First of all - use enums with FlagAttribute. That's what it's for.

[Flags] public enum Time {     None = 0     Current = 1,     Past = 2,     Future = 4     All = 7 } 

Testing then is done like this:

if ( (x & Time.Past) != 0 ) 

Or this:

if ( (x & Time.Past) == Time.Past ) 

The latter will work better if "Past" was a combination of flags and you wanted to test them all.

Setting is like this:

x |= Time.Past; 

Unsetting is like this:

x &= ~Time.Past; 
like image 20
Vilx- Avatar answered Oct 03 '22 00:10

Vilx-