本文介绍了将 String[] 转换为 byte[] 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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};

推荐答案

这应该有效:

byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();

使用Convert.ToByte,您可以指定基数从中转换,在你的情况下,是 16.

using Convert.ToByte, you can specify the base from which to convert, which, in your case, is 16.

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

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();

这篇关于将 String[] 转换为 byte[] 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:49