2016-02-23 31 views
2

我想发送hex命令到我的设备,因为它只能理解hex发送字符串到它的十六进制等效

正因为如此我设法创建一个可以验证,如果用户输入这是一个string有效相应hex功能。问题是here

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

使用ASCIIEncoding类convtert字符串字节 的阵列可以传送。

代码:

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) 

你并不需要的值隐蔽,以十六进制,在这种情况下HEX是 mearly显示同样的事情不同的方式。

我的代码:

'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 
+0

是交谈的设备将向您介绍一些命令行工具的唯一途径?没有一个API可以发送实际字节? – Plutonix

+0

有一个API,我使用[Terminal](https://sites.google.com/site/terminalbpp/)作为接收器来测试我的系统发送的内容是否真的是十六进制。 –

+1

所以你想要它发送一个字符串的十六进制数字?如果是这样,你想使用哪种编码的字符串? ASCII?如果你不想将它作为字符串发送,那么你完全困惑,因为这就是十六进制。十六进制是一个数值的字符串表示。 –

回答

4

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

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

正如我在上面的评论中提到的那样,这些值只是数值。关于十六进制没有什么特别的。十六进制是表示相同值的另一种方式。通过使用appropriate overload

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

如果你有一个字符串的十六进制数字,你可以一个十六进制数字的字符串表示转换为字节值:换句话说,上面的代码不完全一样的东西,因为这的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) 
+0

哦,是的。那就是我的意思。但是我怎么让'{&HA0,&H03,&H82,&H04,&HD7}取决于用户输入? –

+0

那么,这取决于这些值的含义以及用户打算如何输入它们。你是说你只想让用户输入一串十六进制数字的值? –

+0

是的,先生。虽然有一个API我也希望我的用户输入用于调试目的的值,所以如果用户输入'A0038204D7',它将会像'Dim process_CMD()As Byte = {160,3,130,4,215}'这样我的设备可以收到'A0038204D7' –

相关问题