简体   繁体   中英

How do I convert a string array to a byte array using Array ConvertAll?

I can convert string[] to byte[] like in the following code:

 byte[] k = {255, 150, 155, 255, 255, 255, 255, 255, 255, 255, 55, 55, 15, 55, 155, 55};
 string st = BitConverter.ToString(Array.ConvertAll(k, Convert.ToByte));     
 byte[] kk = new byte[16];
 string[] sts = st.Split('-');            
 for (int i = 0; i < 16; i++)
 {
    kk[i] = Convert.ToByte(sts[i], 16);
 }

But I can't do the same with LINQ like in the code below:

Array.ConvertAll(sts,item=>(byte) Convert.ToByte(item, 16))

How do I make this work in LINQ?

Why is it not working in the "Immediate Window" of Visual Studio?

Lambda expressions do not work in "Immediate" and "Watch" windows.

Your code does work. Maybe you forgot a semicolon:

 var a = Array.ConvertAll(sts, s => Convert.ToByte(s, 16));

Here is the elegant solution to convert from a byte array (or double array) to a string and from string to byte/double array. :)

double[] k = {255, 150, 155, 25, 2, 55, 66};
string st = BitConverter.ToString( Array.ConvertAll(k, Convert.ToByte));

And from string to double array...

double[] kk = Array.ConvertAll(st.Split('-'), s => (double) Convert.ToByte(s, 16));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM