Dynamicaly set byte[] array from a String of Ints

2019-09-16 03:35发布

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?

5条回答
叼着烟拽天下
2楼-- · 2019-09-16 03:54

How about Byte.Parse

for (var i = O; i<datasArray.length; i++) {
    byteArr[i] = Byte.Parse(datasArray[i]);  
}
查看更多
迷人小祖宗
3楼-- · 2019-09-16 04:06

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();
查看更多
ゆ 、 Hurt°
4楼-- · 2019-09-16 04:08

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();
查看更多
萌系小妹纸
5楼-- · 2019-09-16 04:12
static byte[] CommaStringToBytes(string s)
{
  return s.Split(',').Select (t => byte.Parse (t.Trim())).ToArray ();  
}
查看更多
Animai°情兽
6楼-- · 2019-09-16 04:17

ConvertAll is very fast

byte[] byteArr = Array.ConvertAll(datasArray, Byte.Parse);
查看更多
登录 后发表回答