问题
I would like to send hex
commands to my device because it can only understand hex
.
Because of that I manage to create a function that can validate if the users input which is a string
has a valid corresponding hex
. The question is here.
So, by validating if the users input
has a corresponding hex
equivalent I am confident that what my system sends will be read by my device. By searching I realized that it needs to be converted to bytes, it states
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.
My code:
'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)
My Output:
41 30 30 33 38 32 30 34 44 37
Desired output:
A0 03 82 04 D7
回答1:
To send a specific sequence of bytes, don't send a string--just send the bytes:
Dim process_CMD() As Byte = { &HA0, &H03, &H82, &H04, &HD7 }
ComPort.Write(process_CMD, 0, process_CMD.Length)
As I mentioned in the comments above, the values are just numeric values. There is nothing special about hex. Hex is just another way to represent the same values. In other words, the code above does exactly the same thing as this:
Dim process_CMD() As Byte = { 160, 3, 130, 4, 215 }
ComPort.Write(process_CMD, 0, process_CMD.Length)
If you have the hex digits in a string, you can convert a string representation of a hex number to a byte value by using the appropriate overload of the Convert.ToByte
method. However, that only converts one byte at a time, so, first you need to split the string into bytes (two hex digits per byte. For instance:
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)
However, it would be easier if the string had spaces between the bytes. Then you could just use the String.Split
method:
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)
Or, more simply:
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)
来源:https://stackoverflow.com/questions/35567006/send-the-string-to-its-hex-equivalent