Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String[] to byte[] array

I'm trying to convert this string array to byte array.

string[] _str= { "01", "02", "03", "FF"}; to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

I have tried the following code, but it does not work. _Byte = Array.ConvertAll(_str, Byte.Parse);

And also, it would be much better if I could convert the following code directly to the byte array : string s = "00 02 03 FF" to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

like image 586
Ahmad Hafiz Avatar asked May 10 '12 09:05

Ahmad Hafiz


2 Answers

This should work:

byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();

using Convert.ToByte, you can specify the base from which to convert, which, in your case, is 16.

If you have a string separating the values with spaces, you can use String.Split to split it:

string str = "00 02 03 FF"; 
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
like image 123
Botz3000 Avatar answered Oct 19 '22 23:10

Botz3000


Try using LINQ:

byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()
like image 45
Marek Dzikiewicz Avatar answered Oct 20 '22 01:10

Marek Dzikiewicz