Search code examples
c#bitbitset

the char presenting bitset c#


I have a system which should return if first entity is ok or the second one or both of them. I decided to return char ,representing a bitmap : i.e. 00 - no one,01 - the first, 10 the second,11 - both. When I read the values, if the result sits in char res I check res %2 == 1 and res / 2 == 1 My team lead said that it is not readable What do you propose to do it better?


Solution

  • Set up an enum like this:

    [Flags]
    enum myBitSet  : ushort
    { 
        none = 0,
        firstThing = 1,
        secondThing = 2,
        bothThings = 3   // or better firstThing | secondThing
    }
    

    Now you can do things like:

    if ((test & myBitSet.firstThing) == myBitSet.firstThing) 
    {
        // firstThing was set
    }
    

    Which is easier to read because you don't have to remember which bit is which.

    And:

    if ((test & myBitSet.bothThings) > 0) 
    {
        // either firstThing, secondThing or both were set.
    }