简体   繁体   English

如何使用Array ConvertAll将字符串数组转换为字节数组?

[英]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: 我可以像下面的代码一样将string[]转换为byte[]

 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: 但是我不能像下面的代码那样对LINQ进行同样的操作:

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

How do I make this work in LINQ? 如何在LINQ中进行这项工作?

Why is it not working in the "Immediate Window" of Visual Studio? 为什么在Visual Studio的“立即窗口”中不起作用?

Lambda expressions do not work in "Immediate" and "Watch" windows. Lambda表达式在“立即”和“监视”窗口中不起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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