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

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

对于我正在编写的连接到具有三个输出托盘(口袋)的扫描仪的程序,我需要使用 SDK。调用 SDK 后,我收到一个代表口袋状态的整数。要确定此 "pocket" 状态,请参阅文档中的以下内容。

获取输出口袋的状态。要确定口袋是满的还是空的,请使用按位与 (&) 运算符检查返回值。有效值为:

我从来没有用过按位运算符,所以我很茫然。 上述 "Pocket" 结构的值如下:

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;
}

我已经阅读了按位运算符,我知道它们的作用,但我无法针对这种特定情况实施它。

提前谢谢大家。

测试位标志的典型模式是

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

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

例如如果你想测试口袋 #3 是否已满:

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

您可以通过 | 组合标志并测试此类组合标志的部分匹配

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