How to implement this using the bitwise & (and)?

This question already has an answer here:

  • What does the [Flags] Enum Attribute mean in C#? 10 answers

  • Typical patterns for testing bit flags are

    // Entire key match  
    if (returned_value & value_to_test == value_to_test) {
      ...
    }
    
    // Partial key match  
    if (returned_value & value_to_test != 0) {
      ...
    }
    

    Eg if you want to test if pocket #3 is full:

    if (returned_value & POCKET.P3_FULL == POCKET.P3_FULL) {
      ...
    }
    

    You can combine flags via | and test for partial match of such combined flag:

    const int ALL_ARE_FULL = POCKET.P1_FULL | POCKET.P2_FULL | POCKET.P3_FULL;
    
    ...
    
    // Test if any part of the flag is match (i.e. any pocket - at least one - is full)
    // Please, notice != 0 comparison
    if (returned_value & ALL_ARE_FULL != 0) {
       ...
    }
    
    // Compare with this: all three pockets are full
    if (returned_value & ALL_ARE_FULL == ALL_ARE_FULL) {
       ...
    }
    
    链接地址: http://www.djcxy.com/p/54446.html

    上一篇: c#标志比较“只包含”一组

    下一篇: 如何使用按位&(和)来实现这个?