Converting a string array to a byte array

倾然丶 夕夏残阳落幕 提交于 2019-12-24 03:07:39

问题


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. 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.


回答1:


This will fail for anything that can't be parsed by byte.Parse

var str = new[] {"5", "168", "188", "28", "29", "155"};
var byt = str.Select(byte.Parse).ToArray();



回答2:


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:

string[] strings = { "5", "168", "188", "28", "29", "155" };
byte[] bytes = Array.ConvertAll(strings, Byte.Parse);

You can also use LINQ extensions to do it:

string[] strings = { "5", "168", "188", "28", "29", "155" };
bytes = strings.Select(Byte.Parse).ToArray();



回答3:


Assuming you mean that you have a string array like string[] myArray = {"5","168",...};:

myArray.Select(x => byte.Parse(x)).ToArray();

Or:

myArray.Select(byte.Parse).ToArray();



回答4:


Try this

With linq

string[] strings = new[] { "1", "2", "3", "4" };
byte[] byteArray = strings.Select(x =>  byte.Parse(x)).ToArray();

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


来源:https://stackoverflow.com/questions/11268514/converting-a-string-array-to-a-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!