将String 转换为byte 数组
我正在尝试将此字符串数组转换为字节数组。
string[] _str= { "01", "02", "03", "FF"};
to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};
我尝试了以下代码,但它不起作用。 _Byte = Array.ConvertAll(_str, Byte.Parse);
而且,如果我可以将以下代码直接转换为字节数组会更好: string s = "00 02 03 FF"
to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};
这应该工作:
byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();
使用Convert.ToByte
,您可以指定要转换的基数,在您的情况下,为16。
如果你有一个用空格分隔值的字符串,你可以使用String.Split
来分割它:
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()
LINQ是最简单的方法:
byte[] _Byte = _str.Select(s => Byte.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture) ).ToArray();
如果你有一个string s = "0002FF";
你可以用这个答案
如果您愿意,仍然可以使用Array.ConvertAll
,但必须指定base 16.所以
_Byte = Array.ConvertAll(_str, s => Byte.Parse(s, NumberStyles.HexNumber));
要么
_Byte = Array.ConvertAll(_str, s => Convert.ToByte(s, 16));
如果你想使用ConvertAll,你可以试试这个:
byte[] _Byte = Array.ConvertAll( _str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));
试试这个:
var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();