vb.net - 从一个字节中获取前三位
问题描述
我的问题很简单,我需要将字节的前三位转换为整数(枚举)值。然而,我尝试的事情总是得到 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
解决方案
使用位操作会更容易
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类。
推荐阅读
- kubernetes - Kubernetes AWS Cloudwatch 适配器未获取 EKS HPA 自动缩放的自定义指标值
- python - 为什么 Pygame 从列表索引错误中崩溃?
- ruby-on-rails - 如何在 Rails 中建立接受一个提案的协会?
- android - 'android.view.View android.widget.TextView.findViewById(int)' 在空对象引用上
- visual-studio-code - 有没有办法在 VS Code 中加粗所有标签?
- powershell - 从多行 PS 脚本组装 oneliners
- ios - 类协议扩展仅限于有限数量的类
- php - Wordpress 页面上的未定义索引错误应该在哪里?
- spring-boot - Spring Security SAML 正在抛出响应没有任何可以通过主题验证的有效断言
- python - 模拟 API 调用 python?