Convert string with hex values to byte array

arrays, c#, string

Solution

From Microsoft website: Convert.ToByte Method (String, Int32):

Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer.

In this case you need to tell ToByte method to convert the string from base 16

byte[] t = x.Split().Select(s => Convert.ToByte(s, 16)).ToArray();

Problem

I have this: ``` string x = "0X65 00 0X94 0X81 00 0X40 0X7E 00 0XA0 0XF0 00 0X80 0X2C 00 0XA9 0XA"; ``` And I would like this: ``` byte[] x = {0X65, 00, 0X94, 0X81, 00, 0X40, 0X7E, 00, 0XA0, 0XF0, 00, 0X80, 0X2C, 00, 0XA9, 0XA}; ``` When I try something like: ``` string[] t = x.split(' '); byte[] byte = new byte[t.Legnth]; for (int i = 0; i < byte.Length; i++) { byte[i] = Convert.ToByte(t[i]); } ``` the byte is encoded to some other value. I'm not familiar with byte formats, I'm just trying to go directly from a string of bytes separated by a space to having them in the array.

Original source