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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10531148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:12:14  来源:igfitidea点击:

Convert String[] to byte[] array

c#arraysstringbyte

提问by Ahmad Hafiz

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

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

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

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

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

我已经尝试了以下代码,但它不起作用。 _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};

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

采纳答案by Botz3000

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.

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

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

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

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

回答by Marek Dzikiewicz

Try using LINQ:

尝试使用 LINQ:

byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()

回答by SynerCoder

With LINQ is the simplest way:

使用 LINQ 是最简单的方法:

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

如果您只有一个字符串 string s = "0002FF";,则可以使用此答案

回答by ie.

Try this one:

试试这个:

var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();

回答by Jeppe Stig Nielsen

You can still use Array.ConvertAllif you prefer, but you must specify base 16. So either

Array.ConvertAll如果您愿意,您仍然可以使用,但您必须指定基数 16。所以要么

_Byte = Array.ConvertAll(_str, s => Byte.Parse(s, NumberStyles.HexNumber));

or

或者

_Byte = Array.ConvertAll(_str, s => Convert.ToByte(s, 16));

回答by Nadir Sampaoli

If you want to use ConvertAll you could try this:

如果你想使用 ConvertAll 你可以试试这个:

byte[] _Byte = Array.ConvertAll<string, byte>(
    _str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));