Reputation: 3669
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.
Upvotes: 4
Views: 27769
Reputation: 700152
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();
Upvotes: 6
Reputation: 148110
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);
}
Upvotes: 2
Reputation: 50215
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();
Upvotes: 12
Reputation: 56536
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();
Upvotes: 2