C# 用位掩码标识特定的二进制数

C# 用位掩码标识特定的二进制数,c#,binary,bit-manipulation,bit,bitmask,C#,Binary,Bit Manipulation,Bit,Bitmask,我试图使用以下位掩码识别CANopen电机控制器中的状态 //x means that the value of the bit doesn't matter and is set to 0 NOT_READY_TO_SWITCH_ON = 0, //xxxx xxxx x0xx 0000 - Not ready to switch on (decimal value = 0) SWITCH_ON_DISABLED = 64, //xxxx xxxx x1xx 0000 - S

我试图使用以下位掩码识别CANopen电机控制器中的状态

//x means that the value of the bit doesn't matter and is set to 0
NOT_READY_TO_SWITCH_ON = 0,    //xxxx xxxx x0xx 0000 - Not ready to switch on (decimal value = 0)
SWITCH_ON_DISABLED = 64,       //xxxx xxxx x1xx 0000 - Switch on disabled (decimal value = 64)
READY_TO_SWITCH_ON = 33,       //xxxx xxxx x01x 0001 - Ready to switch on (33)
SWITCHED_ON = 35,              //xxxx xxxx x01x 0011 - Switched on (35)
OPERATION_ENABLED = 39,        //xxxx xxxx x01x 0111 - Operation enabled (39)
QUICK_STOP_ACTIVE = 7,         //xxxx xxxx x00x 0111 - Quick stop active (7)
FAULT_REACTION_ACTIVE = 15,    //xxxx xxxx x0xx 1111 - Fault reaction active (15)
FAULT = 8,                     //xxxx xxxx x0xx 1000 - Fault (8)
我收到一个数字,我在上面应用位掩码来尝试识别上面的状态,但我无法理解应该如何做

下面的代码是我尝试在C#中实现它的代码:

但是这样做,我最终得到的不是一个,而是一组状态,我想,这是预期的,因为应用了例如,位掩码0(未准备好)将始终为任何数字生成true(使用and时)


我是否做了一些根本错误的事情,或者使用位掩码根本不可能做到这一点?我也不确定在掩码中将标有x的位设置为0是否正确。

你说得对-你不能用掩码测试0;其目的可能是所有零都具有特殊含义,仅与此标志匹配,因此您可以通过测试零是否相等来对其进行特殊处理:

if(thingToLookFor==0)返回值==0;

在我看来,这些值并不是要这样解释的。也许有一组基本的标志,它们是它们的组合。甚至可能不是那样。是否有这些值的文档?
foreach (State s in (State[]) Enum.GetValues(typeof(State))) //State[] contains all bitmasks above
{  
   var v = valToCheck & (ushort)s; //valToCheck is the number to apply the bitmask to
   if ((valToCheck & (ushort)s) == (ushort)s) //Apply the bitmask and compare it to bitmask
   {
      stateList.Add(s); //Add to list for trouble. shooting
   }
}