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

时间:2020-10-26 20:06:13

标签: 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 - 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#中实现的代码:

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

但是这样做,我最终得到的是一堆状态,而不是一个状态,我想这是预期的,因为例如应用位掩码0(NOT_READY_TO_SWITCH_ON)对于任何数字(使用和)。

我是从根本上做错了吗,还是使用位掩码根本不可能做到这一点?我也不确定将掩码中标有x的位设置为0是否正确。

1 个答案:

答案 0 :(得分:1)

您是对的-您无法使用遮罩测试0。大概的目的是全零具有仅与该标志匹配的特殊含义,因此您可以通过用零代替测试平等来特殊化它:

if (thingToLookFor == 0) return value == 0;