Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with hex values to byte array

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.

like image 825
user2634703 Avatar asked Dec 04 '22 06:12

user2634703


1 Answers

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();
like image 71
Ulugbek Umirov Avatar answered Dec 11 '22 09:12

Ulugbek Umirov