0

Is there a way to convert any possible string value to hex in VB.net.

For instance, I've tried this:

 Convert.ToInt32("hello", 16)

But this throws an error saying "Could not find any recognizable digits".

I would like it to return 68656c6c6f, which is a hex representation of the characters in the string.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
user2276280
  • 603
  • 2
  • 10
  • 24

1 Answers1

3

You can get the bytes of the string and then convert each byte to a string. The easiest (but not most efficient way) would be something like this:

Private Function GetHexString(Source As String) As String
    Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes(Source)
    Return BitConverter.ToString(b).Replace("-", "")
End Function
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • Know this wasn't part of the original question, but how would I go about converting this result back to the original string? Would I just need to call System.Text.Encoding.UTF8.GetString(b)? – user2276280 Feb 04 '15 at 15:05