最近在搞上位机和电子秤之间的RS232通讯,涉及到解析出字符数组转成ascii码的问题,如何操作,用下列程序搞定
static void Main(string[] args)
{
//1.需要解析的字符
string hex = "02 20 20 20 20 33 33 35 01 80 20 30 20 20 20 20 20 30 2E 32 38 0D 0A";
List<byte> lists = new List<byte>();
string s=null;
//2.去除字符之间的空格
for (int i = 0; i < hex.Length; i++)
{
if(hex[i]!=' ')
{
s += hex[i];
}
}
hex = s;
StringBuilder sb = new StringBuilder();
//3.将字符两个一组进行分类,并转成字节
for (int i = 0; i < hex.Length / 2; i++)
{
string str = hex.Substring(i * 2, 2);
//sb.Append(str+"/");
byte b = Convert.ToByte(str, 16); //转16进制
lists.Add(b);
}
// Console.WriteLine(lists[1]);
//4.将对应字节转成相应的ascii码
List<char> listchar = new List<char>();
foreach (byte item in lists)
{
char a = Convert.ToChar(item);
listchar.Add(Convert.ToChar(item)); //将byte转成字符
}
//5.显示ascii码
for (int i = 0; i < listchar.Count; i++)
{
Console.Write(listchar[i]);
}
Console.ReadKey();
}