Checking for bit flags

后端 未结 3 2046
萌比男神i
萌比男神i 2020-12-21 14:41

I\'m trying to check for a bit in a flags value of which flags can be |\'d together. So far i\'m using this

 if ((someclass.flags | CONST_SOMEFLAG) == somecl         


        
相关标签:
3条回答
  • 2020-12-21 14:46

    What you want to know is, if the flag bit is set among all the other possibly set or unset bits. The canonical way to do this, is to bitwise and (&) test for being nonzero

    if( someclass.flags & CONST_SOMEFLAG )
    
    0 讨论(0)
  • 2020-12-21 14:57

    Use bitwise OR to set the flags, use bitwise AND to test, like this:

    if (someclass.flags & CONST_SOMEFLAG) ...

    0 讨论(0)
  • 2020-12-21 14:59

    That will work fine, but it's more conventional to use &:

    if (flags & MASK) . . .
    

    This is likely because on some processors testing a register for != 0 is faster than testing for equality with a stored value.

    0 讨论(0)
提交回复
热议问题