Dynamicaly set byte[] array from a String of Ints

2019-09-16 04:05发布

问题:

i usualy set my byte[] arrays like this:

byte[] byteArr = { 123, 234, 123, 234, 123, 123, 234 };

now, my problem, i am getting the datas that have to be stored into the array as a string.

example:

string datas = "123, 234, 123, 234, 123, 123, 234";

i would like to do something like:

byte[] byteArr = { datas };

with no luck...

I tried exploding the string to array of strings, then convert each value to Int before storing into each array field. with no luck:

for (var i = O; i<datasArray.length; i++) {
    byteArr[i] = Int32.Parse(datasArray);  //error, cannot convert int to byte
}

how can i do please?

回答1:

You can use a simple Regex to get the numbers from a string

string datas = "123, 234, 123, 234, 123, 123, 234";
byte[] byteArr = Regex.Matches(datas, @"\d+").Cast<Match>()
                .Select(m => byte.Parse(m.Value))
                .ToArray();


回答2:

How about Byte.Parse

for (var i = O; i<datasArray.length; i++) {
    byteArr[i] = Byte.Parse(datasArray[i]);  
}


回答3:

ConvertAll is very fast

byte[] byteArr = Array.ConvertAll(datasArray, Byte.Parse);


回答4:

static byte[] CommaStringToBytes(string s)
{
  return s.Split(',').Select (t => byte.Parse (t.Trim())).ToArray ();  
}


回答5:

There's also Convert.ToByte(string val)

string datas = "123, 234, 123, 234, 123, 123, 234";

byte[] byteArr = datas.Split(',').Select(b => Convert.ToByte(b)).ToArray();