Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

I have tried the following code, but it does not work. _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};

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...