转换的String []为byte []数组 [英] Convert String[] to byte[] array
问题描述
我想这个字符串数组转换为字节数组。
I'm trying to convert this string array to byte array.
的String [] _STR = {01,02,03,FF};
到字节[] _Byte = {为0x1,0X2,0x3中,为0xFF};
我曾尝试以下code,但它不工作。
_Byte = Array.ConvertAll(_STR,Byte.Parse);
I have tried the following code, but it does not work.
_Byte = Array.ConvertAll(_str, Byte.Parse);
和也,这将是更好,如果我能直接Ç以下$ C $转换为字节数组:字符串s =00 02 03 FF
到字节[] _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.
如果你有一个字符串使用空格隔开的值,可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.string.split.aspx\"><$c$c>String.Split$c$c>分裂的:
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 []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!