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};
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();
尝试使用LINQ:
byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()
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
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));
If you want to use ConvertAll you could try this:
byte[] _Byte = Array.ConvertAll<string, byte>(
_str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));
试试这个:
var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.