[英]Converting a string array to a byte array
Ok, before anyone attempts to label this as a duplicate, I am not asking for a string to a byte array. 好的,在任何人尝试将其标记为重复项之前,我都没有要求将字节串添加到字节数组。 I want a string array, containing something similar like this: {"5","168","188","28","29","155"} to be converted to a byte array. 我想要一个包含类似于以下内容的字符串数组:{“ 5”,“ 168”,“ 188”,“ 28”,“ 29”,“ 155”}被转换为字节数组。 I have searched, and was only able to find string to byte array, which is quite different. 我已经搜索过了,但是只能找到字符串到字节数组的字符串,这是完全不同的。 Thanks. 谢谢。
Edit: the array will be preset so that each member is parsable through byte.Parse, so this is not an issue. 编辑:将预先设置数组,以便每个成员都可以通过byte.Parse进行解析,因此这不是问题。
This will fail for anything that can't be parsed by byte.Parse
对于无法通过byte.Parse
解析的任何内容,这将失败。
var str = new[] {"5", "168", "188", "28", "29", "155"};
var byt = str.Select(byte.Parse).ToArray();
You have to parse each string into a byte and put in a new array. 您必须将每个字符串解析为一个字节,然后放入一个新数组。 You can just loop though the items and convert each one: 您可以循环浏览各个项目并转换每个项目:
string[] strings = { "5", "168", "188", "28", "29", "155" };
byte[] bytes = new byte[strings.length];
for (int i = 0; i < strings.Length; i++) {
bytes[i] = Byte.Parse(strings[i]);
}
You can also use the Array.ConvertAll
method for this: 您也可以为此使用Array.ConvertAll
方法 :
string[] strings = { "5", "168", "188", "28", "29", "155" };
byte[] bytes = Array.ConvertAll(strings, Byte.Parse);
You can also use LINQ extensions to do it: 您也可以使用LINQ扩展来做到这一点:
string[] strings = { "5", "168", "188", "28", "29", "155" };
bytes = strings.Select(Byte.Parse).ToArray();
Assuming you mean that you have a string array like string[] myArray = {"5","168",...};
假设您的意思是您有一个字符串数组,例如string[] myArray = {"5","168",...};
: :
myArray.Select(x => byte.Parse(x)).ToArray();
Or: 要么:
myArray.Select(byte.Parse).ToArray();
Try this 尝试这个
With linq 与linq
string[] strings = new[] { "1", "2", "3", "4" };
byte[] byteArray = strings.Select(x => byte.Parse(x)).ToArray();
Without linq 没有linq
string[] strings = { "1", "2", "3", "4" };
byte[] bytArr = new byte[strings.Length];
int i = 0;
foreach(String text in strings)
{
bytArr[i++] = byte.Parse(text);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.