user2276280
user2276280

Reputation: 601

Convert string of byte array back to original string in vb.net

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?

Upvotes: 0

Views: 996

Answers (1)

Blackwood
Blackwood

Reputation: 4534

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

Upvotes: 2

Related Questions