Reputation: 368
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};
Upvotes: 9
Views: 35019
Reputation: 39600
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();
Upvotes: 14
Reputation: 5555
If you want to use ConvertAll you could try this:
byte[] _Byte = Array.ConvertAll<string, byte>(
_str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));
Upvotes: 1
Reputation: 61912
You can still use Array.ConvertAll
if you prefer, but you must specify base 16. So either
_Byte = Array.ConvertAll(_str, s => Byte.Parse(s, NumberStyles.HexNumber));
or
_Byte = Array.ConvertAll(_str, s => Convert.ToByte(s, 16));
Upvotes: 1
Reputation: 6101
Try this one:
var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();
Upvotes: 0
Reputation: 12766
With LINQ is the simplest way:
byte[] _Byte = _str.Select(s => Byte.Parse(s,
NumberStyles.HexNumber,
CultureInfo.InvariantCulture)
).ToArray();
If you have a single string string s = "0002FF";
you can use this answer
Upvotes: 2
Reputation: 2884
Try using LINQ:
byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()
Upvotes: 4