我的问题很简单,我需要将字节的前三位转换为整数(枚举)值。然而,我尝试的东西总是得到一个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发布于 2019-05-28 20:07:36
使用位运算会更容易。
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类。
https://stackoverflow.com/questions/56341557
复制相似问题