Dynamicaly set byte[] array from a String of Ints

南楼画角 提交于 2019-12-25 13:15:36

问题


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


来源:https://stackoverflow.com/questions/32248713/dynamicaly-set-byte-array-from-a-string-of-ints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!