Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

Hex to byte converter

Ive written a simple line which converts a byte array to a hex string:-
          urlSafe = BitConverter.ToString(byt2Convert).Replace("-", "")

However I have no idea how to convert back to a byte array? Does anyone?

I cant seem to find any example code as simple as converting it from byte to string.

Any ideas?

Thank you
Avatar of deadlyDev
deadlyDev
Flag of Spain image

Straight from http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array
public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length).
           Where(x => 0 == x % 2).
           Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).
           ToArray();
}

Open in new window

Here is another similar technique that doesn't use lamba expressions


' There's no easy way to convert a hex byte string back into
            ' a byte array, so we have parse each byte
            ReDim in_buf((message.Length \ 2) - 1)
            For i As Integer = 0 To in_buf.Length - 1
                in_buf(i) = Byte.Parse(message.Substring(i * 2, 2), Globalization.NumberStyles.HexNumber)
            Next

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of 1303gun
1303gun
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial