【问题标题】:Determine what bits are high in Integer?确定整数中的高位?
【发布时间】:2015-06-08 16:48:55
【问题描述】:

我有一个从运动控制器读取的 32 位整数。该整数表示在控制器中设置的错误位。我有九 (9) 个错误,或者可以在任何时候设置为高的错误位。在任何情况下,可以同时设置一个或所有九个位,或两者之间的任何组合。很明显,识别存在错误很容易,因为如果 Integer 的值 > 0,那么我们就知道存在错误。它出现的困难部分是如何识别设置了哪些错误(位),因为有无数不同的位组合可以在任何时候设置为高电平。我开始尝试屏蔽(如果 Integer > 0 And

【问题讨论】:

标签: vb.net binary integer


【解决方案1】:

您可以使用位操作和计数器来确定设置了哪些位,例如:

int[] set_bits = new int[9]
int currentBit = 0
for (int i = 0; i < 32; i++)
{
    firstBit = errorNumber & 0x1   //firstBit >= 1 only if it is set
    if (firstBit >= 1)
    {
       set_bits[currentBit] = 1
       currentBit++
    }

    errorNumber = errorNumber >> 1   //shift the bits down by one for the next bit
}

那么就可以根据设置的set_bits的索引来进行操作了。抱歉,我不熟悉 VB,但我很肯定 VB 有类似的东西,如果不完全一样的话。我认为移位和二进制运算符的一般概念是您正在寻找解决这个问题的。

这里是logical bitwise operators ('and'-ing numbers togetherarithmatic operations (bit shifting numbers)

【讨论】:

  • 您不需要所有这些代码,BitArray 可以完成所有这些:Dim bits As New BitArray({errorNumber})
【解决方案2】:

您想要一个带有适当掩码的按位与运算:

if error bit 6:
00111010 <-- input from your controller
00100000 <-- mask value for error bit 6
--------
00100000 <-- output bits are set only where the input matches the mask


if no error bit 6:
00011010 <-- input from your controller
00100000 <-- mask value for error bit 6
--------
00000000 <-- output bits are set only where the input matches the mask

我没有 VB.Net 方便检查,但 https://stackoverflow.com/a/4046492/478656 建议 AND 运算符可以工作。 (32 是刚刚设置的第 6 位的整数值)

if (errorValue AND 32) = 32 Then Checkbox1.checked = True

您可能会从解释层中受益,告诉您这些位的含义(例如,位 6 是“电机烧坏”,然后设置一个布尔值“motorBurntOutFlag = true”,所以您不是在猜测 -魔法数字。

例如https://stackoverflow.com/a/666254/478656

Enum controllerErrors as Integer
    powerFail = 2
    incompatibleCommand = 32
    ...
End Enum

if (errorValue AND controllerErrors.powerFail) > 0 Then
    'code
end if

【讨论】:

    【解决方案3】:

    一种简洁的方法是定义一个枚举,其中包含所有相关的错误 用他们的一点。

    Public Enum MotionControlerErrors As Integer
    
      NoMorePower = 1 << 2
      Explosion = 1 << 6 
      SomeOtherError = 1 << 7
    
       ...
    
    End Enum
    

    然后你可以用这种方式从你的错误中构建一个位列表:

    Function BuildMaskList( ErrorResult As integer ) As List(Of Boolean)
      Dim ResultList As New List( Of Boolean) 
      For Each err In MotionControlerErrors
        ResultList.Add ( (err AND ErrorResult) = err )
      End For
      Return ResultList
    End Function
    

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2021-03-09
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多