Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enums with bit flags

I have an enum declaration using bit flags and I cant exactly figure out on how to use this.

enum  {   kWhite   = 0,   kBlue    = 1 << 0,   kRed     = 1 << 1,   kYellow  = 1 << 2,   kBrown   = 1 << 3, }; typedef char ColorType; 

I suppose to store multiple colors in one colorType I should OR the bits together?

ColorType pinkColor = kWhite | kRed; 

But suppose I would want to check if pinkColor contains kRed, how would I do this?

Anyone care to give me an example using the provided ColorType example ?

like image 453
Oysio Avatar asked Aug 19 '10 17:08

Oysio


People also ask

What is a Flag enum?

The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

What is the role of Flag attribute in enum?

The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value. All the possible combination of values will come. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value.

What is a bitmask enum?

Bitmask enums are a way of organizing flags. Like having a collection of booleans without having to keep track of a dozen different variables. They are fast and compact, so generally good for network related data.


1 Answers

Yes, use bitwise OR (|) to set multiple flags:

ColorType pinkColor = kWhite | kRed; 

Then use bitwise AND (&) to test if a flag is set:

if ( pinkColor & kRed ) {    // do something } 

The result of & has any bit set only if the same bit is set in both operands. Since the only bit in kRed is bit 1, the result will be 0 if the other operand doesn't have this bit set too.

If you need to get whether a particular flag is set as a BOOL rather than just testing it in an if condition immediately, compare the result of the bitwise AND to the tested bit:

BOOL hasRed = ((pinkColor & kRed) == kRed); 
like image 194
walkytalky Avatar answered Oct 19 '22 16:10

walkytalky