4

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.

10
  • 1
    Please provide a more specific example. What do you mean? Commented Jun 29, 2012 at 20:28
  • See this answer on serialization: stackoverflow.com/q/1446547/228080 Commented Jun 29, 2012 at 20:28
  • 1
    Do you have a string array, like new string[] {"5","168","188"} or a string containing an array like syntax, like "[5,168,188]"? Commented Jun 29, 2012 at 20:29
  • Without more context - specifically of what you are trying to achieve with this transformation, we can't really help. Commented Jun 29, 2012 at 20:30
  • 4
    You can still edit your question and clarify it. Commented Jun 29, 2012 at 20:32

4 Answers 4

12

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();
Sign up to request clarification or add additional context in comments.

1 Comment

worked for me, i was debugging my API response in bytes, So i logged the bytes to textpad and trying to rebuild the response bytes.
6

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();

Comments

2

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();

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.