Click here to Skip to main content
14,872,121 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Just for an example
Inside the Textbox.Text I have:

String = "01-23-45-67-89"


I want to convert it to Byte array with same value with &H
Byte = " &H01, &H23, &H45, &H67, &H89"


any suggestion please.

What I have tried:

Private Function HexStringToBytes(ByVal input As String) As Byte()
 
    Dim byteStrings() As String = input.Split(New Char() {","c})
    If (byteStrings.Length > 0) Then
        Dim retVal() As Byte = CType(Array.CreateInstance(GetType(Byte), byteStrings.Length), Byte())
        Dim idx As Integer = 0
        For Each byteString As String In byteStrings
            retVal(idx) = Convert.ToByte(byteString, 16)
            idx += 1
        Next
        Return retVal
    End If
    Return New Byte() {}
End Function
Posted
Updated 23-Mar-21 23:09pm
v2
Comments
jsc42 11-Mar-21 5:16am
   
Are you trying to create a string with "&Hxx" texts in it, as per your description; or an array of bytes as per your sample code?
If it is the string, then you can do a simple text conversion e.g. Dim byteString As String = "&H" & inputString.Replace("-", ", &H")
If it is the array of bytes, then I'll let someone else reply as the technique is slightly harder and will need something in a 'Solution' section rather that a 'Comment' section.

There is a function in .NET which might help: SoapHexBinary.Parse(String) Method (System.Runtime.Remoting.Metadata.W3cXsd2001) | Microsoft Docs[^] - it requires spaces instead of hyphens, but string.Replace will deal with that.
VB
Dim s As String = "FF FF FF FF 82 00 01 02 03 04 00 05 01 02 03 04 05 ee ed"
Dim bytes As Byte() = SoapHexBinary.Parse(s).Value
   
Same as yesterday[^], but with a different increment:
VB.NET
Shared Function HexStringToBytes(ByVal hexString As String) As Byte()
    Dim result As New List(Of Byte)()
    For i As Integer = 0 To hexString.Length - 1 Step 3
        result.Add(Convert.ToByte(hexString.Substring(i, 2), 16))
    Next
    Return result.ToArray()
End Function
Or, using a variation of your function:
VB.NET
Shared Function HexStringToBytes(ByVal input As String) As Byte()
    Dim byteStrings() As String = input.Split(New Char() {"-"c})
    Dim retVal() As Byte = Array.ConvertAll(byteStrings, Function(s) Convert.ToByte(s, 16))
    Return retVal
End Function


EDIT: Based on your comment, you are actually trying to convert an array of bytes to a string. Again, I gave you that function yesterday:
VB.NET
Shared Function BytesToHexString(ByVal bytes As Byte()) As String
    Dim sb As New StringBuilder()
    For i As Integer = 0 To bytes.Length - 1
        sb.Append(bytes(i).ToString("X2"))
    Next
    Return sb.ToString()
End Function
   
v3
Comments
Nicky Ralph 11-Mar-21 6:47am
   
I tried to use the code above and get the value of textbox1 to show it on Richtext1, I got and error " dimensional array of Byte cannot be converted to string"
Private Sub Button1_Click(
        'RichTextBox1.Text = HexStringToBytes(TextBox1.Text)
End Sub
Richard Deeming 11-Mar-21 6:51am
   
Well, once again, you've described things the wrong way round.

Your question is about converting a string to an array of bytes.

That error tells me you are trying to convert an array of bytes to a string.

Stop randomly typing code, and start thinking about what you are trying to do!
Richard Deeming 11-Mar-21 7:04am
   
The textbox text is a STRING. It is NOT a byte array!

You want to convert a byte array to a string. As I showed you yesterday.
Nicky Ralph 11-Mar-21 7:08am
   
YES, I want to convert string into byte array with same value of hex. something like this, Inside the textbox1.text is a HEX VALUE

TEXTBOX1.TEXT = "A1-B2-C3-D4-E5"


I want to convert it into byte like

byte() ={&HA1, &HB2, &HC3, &HD4, &hE5}
Richard Deeming 11-Mar-21 7:09am
   
No, you don't.

You want to convert the string to a byte array - which I've already shown you how to do - and then convert the byte array back to a string - which I've also shown you how to do.

You cannot store a byte array in a string property!
Nicky Ralph 11-Mar-21 7:14am
   
Thank you, I'll try it again, I'll update you.
Nicky Ralph 11-Mar-21 7:16am
   
This is what I did

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Public Class Form1
    Shared Function HexStringToBytes1(ByVal hexString As String) As Byte()
        Dim result As New List(Of Byte)()
        For i As Integer = 0 To hexString.Length - 1 Step 3
            result.Add(Convert.ToByte(hexString.Substring(i, 2), 16))
        Next
        Return result.ToArray()
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RichTextBox1.Text = HexStringToBytes(TextBox1.Text)
    End Sub
End Class
Richard Deeming 11-Mar-21 7:19am
   
I give up. You're clearly not prepared to listen.

You CANNOT store a BYTE ARRAY in a STRING property.

You have a function to get from A to B, and another function to get from B to C. And yet somehow you cannot work out how to get from A to C.

This is basic stuff. Perhaps you should consider switching to a different course - not everyone is cut out for writing code.
Nicky Ralph 11-Mar-21 7:45am
   
I did this:
Dim HexArray as Byte() = New byte() { }
how can i get the value of textbox1.text using this

HexStringToBytes(input)
Richard Deeming 11-Mar-21 7:50am
   
Seriously? How long did you spend as a child trying to force the square peg into the round hole?

You CANNOT store a byte array in a string property. You need to convert the byte array to a string first. Which I have already shown you how to do.
Ralf Meier 11-Mar-21 9:04am
   
@Richard:
I admire your patience ...
Ralf Meier 11-Mar-21 9:07am
   
Why don't you listen to what Richard wrote to you ?
Don't you know the difference between those Types of Variables ?

What I don't understand :
You have a String why those values inside. Why do you first convert it to an Array and after this want it back as a string ?
If you can answer this I suppose you find the real answer by yourself ...
sorry for that ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900