Reputation: 11
I have data from Serial, the data are : 7 5 16 0 242 48 44 10 109
Those data are sent in string format.
I need to re-convert the string to it decimal value. But data with value 242 is read as 63. Also for data from 128 to 255 are not correctly converted to it decimal value.
I use :
byte[] bytes = Encoding.GetEncoding("Windows-1252").GetBytes(rxString);
and also :
byte[] bytes = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(rxString);
byte[] bytes = Encoding.ASCII.GetBytes(rxString)
All are not working. Please help me.
Upvotes: 1
Views: 117
Reputation: 916
++ use Array.ConvertAll<TInput, TOutput> Method (TInput[], Converter<TInput, TOutput>)
string[] val = "7 5 16 0 242 48 44 10 109".Split(' ');
byte[] temp = Array.ConvertAll(val, byte.Parse);
or
string val = "7 5 16 0 242 48 44 10 109";
byte[] result = Array.ConvertAll(val.Split(' ').Select(c => c).ToArray(), byte.Parse);
Upvotes: 0
Reputation: 9143
If you need array of bytes from this string (I assume from your tries), use this one-liner:
string val = "7 5 16 0 242 48 44 10 109";
byte[] list = val.Split(' ').Select(a => Convert.ToByte(a)).ToArray();
Upvotes: 0
Reputation: 1733
// assuming 'serialData' is your string of values...
var decimals = new List<decimal>();
foreach (var token in serialData.Split(' '))
{
decimals.Add(decimal.Parse(token));
}
// 'decimals' is now a list of the decimal values.
...or if you were looking for byte
values, you could change List<decimal>
to List<byte>
and change decimal.Parse
to byte.Parse
.
Upvotes: 1