Using Bitwise operators on flags

后端 未结 9 1875
生来不讨喜
生来不讨喜 2020-12-23 12:11

I have four flags

Current = 0x1  
Past = 0x2  
Future = 0x4  
All = 0x7

Say I receive the two flags Past and Future (setFlags(PAST

相关标签:
9条回答
  • 2020-12-23 12:48
    if ((flags & PAST) == PAST)
    {
      // PAST is there
    }
    
    if ((flags & CURRENT) != CURRENT)
    {
      // CURRENT is not there
    }
    
    0 讨论(0)
  • 2020-12-23 12:49

    I think what is missing is to take "all" but one

    [Flags]
    public enum Time
    {
        None = 0,
        Current = 1,
        Past = 1 << 1, // 2, 10 binary
        Future = 1 << 2, // 4, 100 binary
        All = Current | Past | Future
    }
    

    Then with the above flags enum, you can do

    var notNow= Time&~Time.Current;
    
    0 讨论(0)
  • 2020-12-23 12:50

    If you want all bits in the test mask to match:

    if((value & mask) == mask) {...}
    

    If you want any single bit in the test mask to match:

    if((value & mask) != 0) {...}
    

    The difference is most apparent when you are testing a value for multiple things.

    To test for exclusion:

    if ((value & mask) == 0) { }
    
    0 讨论(0)
提交回复
热议问题