Wabbitseason
Wabbitseason

Reputation: 5691

More elegant way to store bits in a byte in C#?

I want to use 5 boolean values in a byte variable in C#. I have come up with the below code which works fine, but it's rather ugly.

byte myDataMask = 0;
if (isOne) myDataMask |= 1;
if (isTwo) myDataMask |= 2;
if (isFour) myDataMask |= 4;
if (isEight) myDataMask |= 8;
if (isSixteen) myDataMask |= 16;

Is there a nicer, more elegant, shorter way to express the same?

Upvotes: 1

Views: 185

Answers (1)

jdweng
jdweng

Reputation: 34433

How about an enumeration :

        public enum Mask
        {
            IS_NONE = 0,
            IS_ONE = 1,
            IS_TWO = 2,
            IS_FOUR = 4,
            IS_EIGHT = 8,
            IS_SIXTEEN = 16
        }
        private static void Main()
        {

            byte data = 0x04;

            switch ((Mask)data)
            {
                case Mask.IS_NONE :
                    break;

                case Mask.IS_ONE :
                    break;
                case Mask.IS_TWO :
                    break;
                case Mask.IS_FOUR :
                    break;
                case Mask.IS_EIGHT :
                    break;
                case Mask.IS_SIXTEEN :
                    break;


            }


        }

Upvotes: 1

Related Questions