我有来自Serial的数据,数据是:7 5 16 0 242 48 44 10 109
这些数据以字符串格式发送。
我需要将字符串重新转换为十进制值。 但值为242的数据读为63。 此外,对于128到255之间的数据,未正确转换为十进制值。
我用:
byte[] bytes = Encoding.GetEncoding("Windows-1252").GetBytes(rxString);
还有:
byte[] bytes = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(rxString);
byte[] bytes = Encoding.ASCII.GetBytes(rxString)
一切都行不通。请帮帮我。
答案 0 :(得分:1)
// 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.
...或者,如果您要查找byte
个值,可以将List<decimal>
更改为List<byte>
并将decimal.Parse
更改为byte.Parse
。
答案 1 :(得分:0)
如果您需要此字符串中的字节数组(我假设您的尝试),请使用此单行代码:
string val = "7 5 16 0 242 48 44 10 109";
byte[] list = val.Split(' ').Select(a => Convert.ToByte(a)).ToArray();
答案 2 :(得分:0)
++使用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);
或
string val = "7 5 16 0 242 48 44 10 109";
byte[] result = Array.ConvertAll(val.Split(' ').Select(c => c).ToArray(), byte.Parse);