vb.net - 将字符串发送到其等效的十六进制值

标签 vb.net serial-port hex byte

我想向我的设备发送 hex 命令,因为它只能理解 hex

因此,我设法创建一个函数,可以验证用户输入的 string 是否具有有效对应的 hex 。问题是 here

因此,通过验证 users input 是否具有相应的 hex 等效项,我确信我的系统发送的内容将被我的设备读取。 By searching 我意识到它需要转换为字节,它指出

Use the ASCIIEncoding class to convtert strings to an array of bytes you can transmit.

Code:

Dim str as String = "12345678"
Dim bytes() as Byte = ASCIIEncoding.ASCII.GetBytes(strNumbers)
' Then Send te bytes to the reader
sp.Write(bytes, 0, bytes.Length)

You do not need to covert the values to HEX, in this case HEX is mearly a different way of displaying the same thing.

我的代码:

'This is a string with corresponding hex value
Dim msg_cmd as string  = "A0038204D7" 
'Convert it to byte so my device can read it
Dim process_CMD() As Byte = ASCIIEncoding.ASCII.GetBytes(msg_cmd) 
'Send it as bytes
ComPort.Write(process_CMD, 0, process_CMD.Length) 

我的输出:

41 30 30 33 38 32 30 34 44 37

期望的输出:

A0 03 82 04 D7

最佳答案

要发送特定的字节序列,不要发送字符串 - 只需发送字节:

Dim process_CMD() As Byte = { &HA0, &H03, &H82, &H04, &HD7 }
ComPort.Write(process_CMD, 0, process_CMD.Length)

正如我在上面的评论中提到的,这些值只是数值。十六进制没有什么特别的。十六进制只是表示相同值的另一种方式。换句话说,上面的代码所做的事情与以下完全相同:

Dim process_CMD() As Byte = { 160, 3, 130, 4, 215 }
ComPort.Write(process_CMD, 0, process_CMD.Length)

如果字符串中有十六进制数字,则可以使用 appropriate overload 将十六进制数字的字符串表示形式转换为字节值。 Convert.ToByte 方法的。但是,一次只能转换一个字节,因此,首先您需要将字符串拆分为字节(每个字节两个十六进制数字。例如:

Dim input As String = "A0038204D7"
Dim bytes As New List(Of Byte)()
For i As Integer = 0 to input.Length Step 2
    bytes.Add(Convert.ToByte(input.SubString(i, 2), 16)
Next
Dim process_CMD() As Byte = bytes.ToArray()
ComPort.Write(process_CMD, 0, process_CMD.Length)

但是,如果字符串的字节之间有空格,则会更容易。然后你可以使用 String.Split 方法:

Dim input As String = "A0 03 82 04 D7"
Dim hexBytes As String() = input.Split(" "c)
Dim bytes As New List(Of Byte)()
For Each hexByte As String in hexBytes
    bytes.Add(Convert.ToByte(hexByte, 16)
Next
Dim process_CMD() As Byte = bytes.ToArray()
ComPort.Write(process_CMD, 0, process_CMD.Length)

或者,更简单地说:

Dim input As String = "A0 03 82 04 D7"
Dim process_CMD() As Byte = input.Split(" "c).Select(Function(x) Convert.ToByte(x, 16)).ToArray()
ComPort.Write(process_CMD, 0, process_CMD.Length)

关于vb.net - 将字符串发送到其等效的十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567006/

相关文章:

c# - 如何将C#中的符号“?”转换为vb.net?

vb.net - 自定义水印文本框表现异常

c# - 串行端口 : Send in Bytes or Characters?

c++ - 创建和写入文件 C++

groovy - 在 Groovy 中将整数转换为十六进制字符串

.net - dynamic-linq Select 中的字符串连接

java - 如何在 java/shell 中的 javax.comm.PortInUseException 后释放串口

c - 0x9B (155decimal) 是一个特殊的控制字符吗?为什么它在 ascii 表中不见了?

C/实时用不同类型的数据初始化内存

vb.net - VB .NET 通过字符串值访问类属性