views:

49

answers:

1

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 ?

+5  A: 

Use bitwise AND (&) to test:

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.

walkytalky
Note: This means that if `pinkColor` is `kRed`, `(pinkColor ` An alternative is to cast the result to C99's `bool` type: `isPink = (bool)(pinkColor ` And a(n admittedly uncommon) way that doesn't assume 1 is in range would use `?:`: `isPink = (pinkColor `
Peter Hosey