Eden_Pierce
Eden_Pierce

Reputation: 43

How to convert ASCII to hexdecimal in VB.NET?

I want to make a program that converts an ASCII string to hexadecimal in VB.NET.

This is what I'm talking about:

There is a form with two textboxes and one button. The user puts in something in ASCII in textbox1, and after hitting the button, textbox2 displays it in hexadecimal.

So input in ASCII on textbox 1: test

Output in hexadecimal in textbox2 after hitting button1: 74657374

Is there a way to do this?

Upvotes: 1

Views: 13672

Answers (2)

user3905907
user3905907

Reputation:

The code that convert string to hex value

Dim str As String = "test"
Dim byteArray() As Byte
Dim hexNumbers As System.Text.StringBuilder = New System.Text.StringBuilder
byteArray = System.Text.ASCIIEncoding.ASCII.GetBytes(str)
For i As Integer = 0 To byteArray.Length - 1
    hexNumbers.Append(byteArray(i).ToString("x"))
Next
MsgBox(hexNumbers.ToString()) ' Out  put will be 74657374

The following code will reverse the operation and verify the output:

Dim st As String = hexNumbers.ToString
Dim com As String = ""
For x = 0 To st.Length - 1 Step 2
    com &= ChrW(CInt("&H" & st.Substring(x, 2)))
Next
MsgBox(com)

Upvotes: 1

Luke Hoffmann
Luke Hoffmann

Reputation: 918

textbox2.Text = ""
For Each c As Char In textbox1.Text
    textbox2.Text &= Convert.ToString(Convert.ToInt32(c), 16)
Next

Upvotes: 1

Related Questions