HypeZ
HypeZ

Reputation: 4127

Converting String to String of Hex and vice-versa in Vb.Net

I need to convert a String of totally random characters in something i can read back! My idea is:

Example String: hi

h (Ascii) -> 68 (hex) 
i (Ascii) -> 69 (hex)

So converting hi i must have 6869

My value is now in Base64 (i got it with a Convert.ToBase64String()), is this "ascii to hex" conversion correct? In base64 i have value like "4kIw0ueWC/+c=" but i need characters only, special characters can mess my system

The vb.net Convert can only translate to base64 string :(

edit: This is my final solution: i got the base64 string inside my enc variable and converted it first in ASCII then in corrispondent Hex using:

Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(enc)
Dim hex As String = BitConverter.ToString(bytes).Replace("-", String.Empty)

After that i reversed this with:

Dim b((input.Length \ 2) - 1) As Byte
For i As Int32 = 0 To b.GetUpperBound(0)
     b(i) = Byte.Parse(input.Substring(i * 2, 2), Globalization.NumberStyles.HexNumber)
Next i
Dim enc As New System.Text.ASCIIEncoding()
result = enc.GetString(b)

After all this i got back my base64string and converted one last time with Convert.FromBase64String(result)

Done! Thanks for the hint :)

Upvotes: 0

Views: 18232

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

First get Byte() from your base64 string:

Dim data = Convert.FromBase64String(inputString)

Then use BitConverter:

String hex = BitConverter.ToString(data)

Upvotes: 2

Related Questions