将String []转换为byte []数组

Ahm*_*fiz 8 c# arrays string byte

我正在尝试将此字符串数组转换为字节数组.

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

我尝试了以下代码,但它不起作用. _Byte = Array.ConvertAll(_str, Byte.Parse);

而且,如果我可以将以下代码直接转换为字节数组会更好: string s = "00 02 03 FF"tobyte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

Bot*_*000 13

这应该工作:

byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();
Run Code Online (Sandbox Code Playgroud)

使用Convert.ToByte,您可以指定要转换的基数,在您的情况下,为16.

如果您有一个用空格分隔值的字符串,您可以使用String.Split它来拆分它:

string str = "00 02 03 FF"; 
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
Run Code Online (Sandbox Code Playgroud)