Search code examples
c#bitwise-operatorsbitwise-and

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


For a program I am writing to connect to a scanner with three output trays (pockets) I need to make use of an SDK. After a call to the SDK I receive an int that represents the status of the pockets. To determine this "pocket" status the following is in the documentation.

Get status of the output pockets. To determine whether a pocket is full or empty, check the returned value using the bitwise AND (&) operator. Valid values are:

  • Csd.POCKET.P1_EMPTY Pocket 1 is empty.
  • Csd.POCKET.P2_EMPTY Pocket 2 is empty.
  • Csd.POCKET.P1_FULL Pocket 1 is full.
  • Csd.POCKET.P2_FULL Pocket 2 is full.
  • Csd.POCKET.P3_EMPTY Pocket 3 is empty.
  • Csd.POCKET.P3_FULL Pocket 3 is full.

I have never used bitwise operators so I am quite at a loss. The values of the above "Pocket" struct are as follows:

public struct POCKET
{
  public const int P1_EMPTY = 1;
  public const int P1_FULL = 16;
  public const int P2_EMPTY = 2;
  public const int P2_FULL = 32;
  public const int P3_EMPTY = 4;
  public const int P3_FULL = 64;
}

I have read up on bitwise operators and I know what they do, but I am at a loss implementing it for this specific case.

Thank you all in advance.


Solution

  • 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) {
      ...
    }
    

    E.g. 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) {
       ...
    }