0

I have a plain text string that I'm converting to a byte array and then to a string and storing in a database.

Here is how I'm doing it:

    Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes("Hello")
    Dim s As String = BitConverter.ToString(b).Replace("-", "")

Afterwards I store the value of s (which is "48656C6C6F") into a database.

Later on, I want to retrieve this value from the database and convert it back to "Hello". How would I do that?

0

1 Answer 1

2

You can call the following function with your hex string and get "Hello" returned to you. Note that the function doesn't validate the input, you would need to add validation unless you can be sure the input is valid.

Private Function HexToString(ByVal hex As String) As String
    Dim result As String = ""
    For i As integer = 0 To hex.Length - 1 Step 2
        Dim num As Integer = Convert.ToInt32(hex.Substring(i, 2), 16)
        result &= Chr(num)
    Next
    Return result
End Function

James Thorpe points out in his comment that it would be more appropriate to use Encoding.UTF8.GetString to convert back to a string as that is the reverse of the method used to create the hex string in the first place. I agree, but as my original answer was already accepted, I hesitate to change it, so I am adding an alternative version. The note about validation of input being skipped still applies.

Private Function HexToString(ByVal hex As String) As String
    Dim bytes(hex.Length \ 2 - 1) As Byte 
    For i As Integer = 0 To hex.Length - 1 Step 2
        bytes(i \ 2) = Byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)
    Next
    Return System.Text.Encoding.UTF8.GetString(bytes)
End Function
Sign up to request clarification or add additional context in comments.

2 Comments

Consider using the ChrW function if you're going to go that route so you can support unicode. Be aware that these functions are hangovers from VB6 though, and you'd be better off using Encoding.UTF8.GetString since it's the "opposite" action of what was used to get the bytes in the first place.
@JamesThorpe: I agree and have added alternative code in my answer. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.