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?
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();
How about Byte.Parse
for (var i = O; i<datasArray.length; i++) {
byteArr[i] = Byte.Parse(datasArray[i]);
}
ConvertAll is very fast
byte[] byteArr = Array.ConvertAll(datasArray, Byte.Parse);
static byte[] CommaStringToBytes(string s)
{
return s.Split(',').Select (t => byte.Parse (t.Trim())).ToArray ();
}
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();