首页 > 解决方案 > 从一个字节中获取前三位

问题描述

我的问题很简单,我需要将字节的前三位转换为整数(枚举)值。然而,我尝试的事情总是得到 0 的回报。这是文件所说的:

Bit 0-3: These bits indicate the connection state.

Value 0 to 14 indicate the connection state. Value 3 = Connected

现在我(从串行设备)得到的响应是 ASCII 十六进制值的编码字节流,所以我首先需要将它从十六进制字符串转换为字节数组,然后从中获取位。到目前为止,这是我的代码:

Dim strResonse As String = "0C03" 'This should result in a connection state value of 3

Dim ConState(2) As Byte
ConState = HexStringToByteArray(strResonse)
Dim int As Integer = ConState(1) << 1 And ConState(1) << 2 And ConState(1) << 3
Debug.Print(int.ToString)


Private Function HexStringToByteArray(ByVal shex As String) As Byte()
    Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
    Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function

标签: vb.nettype-conversionhexbytebit

解决方案


使用位操作会更容易

Dim connectionState As Integer
Dim response As Integer = &HC03

' Get the first 4 bits. 15 in binary is 1111
connectionState = response And 15

如果您的输入确实是一个字符串,则有一种内置方法可以转换为整数。

Dim response As Integer = Convert.ToInt32("C03", 16)

如果你真的想得到一个数组,我建议你使用内置的方法。

Dim allBits As Byte() = BitConverter.GetBytes(response)

还有可以方便的BitArray类。


推荐阅读