【问题标题】:Identifying a specific binary number with bitmask使用位掩码识别特定的二进制数
【发布时间】:2021-02-09 03:06:46
【问题描述】:

我正在尝试使用以下位掩码识别 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) 将始终为任何数字产生 true(当使用和)。

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

【问题讨论】:

  • 这些值在我看来并不像是打算以这种方式解释的。也许有一组基础标志,它们是它们的组合。或者甚至可能不是。是否有这些值的一些文档?

标签: c# binary bit-manipulation bit bitmask


【解决方案1】:

你是对的 - 你不能用面具测试 0;大概意图是所有零都具有仅与此标志匹配的特殊含义,因此您可以通过用零测试 equality 来对其进行特殊处理:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2016-01-10
    • 2020-04-13
    • 2018-11-07
    相关资源
    最近更新 更多