How to use enums with bit flags

后端 未结 1 1193
执笔经年
执笔经年 2020-12-13 19:27

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条回答
  • 2020-12-13 19:46

    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);
    
    0 讨论(0)
提交回复
热议问题