How can I convert a hex string to a byte array?

Blankman picture Blankman · Nov 26, 2008 · Viewed 530.8k times · Source

Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?

Answer

JaredPar picture JaredPar · Nov 26, 2008

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}