-3

So I have a flags Enum

public Enum test
{
   test1 = 1,
   test2 = 2,
   test3 = 4,
   etc.
}

How can I test that one bit, and only one bit is set?

I've 100% done this before but my mind is not working this am!

Liam
  • 27,717
  • 28
  • 128
  • 190

1 Answers1

13

To check that only a single bit is set in a number, the number must (by definition) be a power of two. As such, you can use the following to test:

int intVal = ((int)myEnumFlags);
bool singleBitIsSet = intVal != 0 && (intVal & (intVal-1)) == 0;

My favorite reference for this kind of thing:

http://aggregate.org/MAGIC

spender
  • 117,338
  • 33
  • 229
  • 351
  • 4
    Please note that this won't work when `intVal == 0`. `0` has no bit set but `0 & -1 == 0` – Ahmed KRAIEM Oct 15 '13 at 08:57
  • 1
    "To check that only a single bit is set in a number, the number must (by definition) be a power of two." Unless it's `0` wich isn't a power of 2 but has not bit set. – Ahmed KRAIEM Oct 15 '13 at 08:58
  • @AhmedKRAIEM : you are right. Updated my answer. It might be more efficient to swap the order of the test, depending on which values are more likely. – spender Oct 15 '13 at 09:03
  • made an extension using the code from this answer. can now write `enumvalue.IsSingleFlag` (in addition to `enumvalue.HasFlag`, which Comes with the framework) – Cee McSharpface Aug 23 '16 at 19:18