我的问题很简单,我需要将字节的前三位转换为整数(Enum)值。但是我尝试的事情我总是得到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
答案 0 :(得分:2)
使用位操作会更容易
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类可以派上用场。