2

I'm using C#.

I have a string array as follow: "1,2,3,4,5,..." I'm trying to convert the string array to byte array as follow []{1,2,3,4,5,...} What is the best way to do that?

Thanks.

2

3 Answers 3

7

Try using Linq:

 string source = "1,2,3,4,5";

 byte[] result = source
   .Split(',')
   .Select(item => byte.Parse(item))
   .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

4
byte[] byteArray = str.Select(s => Convert.ToByte(s, 16)).ToArray();

Str represent string[]. If you have string you should string[] str = string.Split(',');

4 Comments

This doesn't compile because the base argument is only applicable when the first argument is a string. In your code, s is type char. I get the following error: Argument 2: cannot convert from 'int' to 'System.IFormatProvider' In addition, this will include the commas as arguments.
@ChrisDunaway Str is string array the question is string array to byte array.
I re-read the question and though the OP used the words "string array", I believe they actually had a string and not a real string[] to begin with. The accepted answer seems to support this assumption. I agree that your answer is valid given that str is really a string[].
@ChrisDunaway I edit it, I'm from mobile so I have limited possibilities for formatting.
2
byte[] result = Array.ConvertAll(str.Split(','), Convert.ToByte);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.