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.

Evyatar
  • 1,107
  • 2
  • 13
  • 36
  • See : http://stackoverflow.com/questions/1763613/convert-comma-separated-string-of-ints-to-int-array – PaulF Oct 25 '16 at 15:53
  • Your answer lies in a previous question: http://stackoverflow.com/questions/10531148/convert-string-to-byte-array – Knight Fall Oct 25 '16 at 15:55

3 Answers3

7

Try using Linq:

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

 byte[] result = source
   .Split(',')
   .Select(item => byte.Parse(item))
   .ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
4
byte[] byteArray = str.Select(s => Convert.ToByte(s, 16)).ToArray();

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

mybirthname
  • 17,949
  • 3
  • 31
  • 55
  • 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. – Chris Dunaway Oct 25 '16 at 18:24
  • @ChrisDunaway Str is string array the question is string array to byte array. – mybirthname Oct 25 '16 at 18:34
  • 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[]`. – Chris Dunaway Oct 25 '16 at 18:37
  • @ChrisDunaway I edit it, I'm from mobile so I have limited possibilities for formatting. – mybirthname Oct 25 '16 at 18:40
2
byte[] result = Array.ConvertAll(str.Split(','), Convert.ToByte);
serhiyb
  • 4,753
  • 2
  • 15
  • 24