views:

770

answers:

6

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.

A: 

you could use AND on it and check if the result is the same as you and with?

Petoj
+2  A: 
if ((flags & PAST) == PAST)
{
  // PAST is there
}

if ((flags & CURRENT) != CURRENT)
{
  // CURRENT is not there
}
CodeMonkey1
Marc Gravell
@Marc Gravell, why would you post this comment and not edit the post for the guy?
Simucal
A: 
(value & Current) == Current
Stuart Branham
+11  A: 

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;
Vilx-
+11  A: 

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) { }
Marc Gravell
Would you give an example with the ~?
Malfist
Actually, might not be needed - updatd
Marc Gravell
+3  A: 

You may also want to add an extension method like this

  enum states {
     Current = 0x1,
     Past = 0x2,
     Future = 0x4,
     All = 0x7
  };

  static bool Is(this states current, states value) {
     return (current & value) == value;
  }

then you can do:

 if(state.Is(states.Past)) {
    // Past
 }
Brian Rasmussen