c# string 和byte[] 转换问题

.Net技术 码拜 8年前 (2016-03-12) 1058次浏览
本人想把通过串口发字符串,现在代码如下:

                                 string txt = "5A A5 05 82 01 04 00 01";//根据空格分割字符串成字符串数组
                  string[] hexWords = txt.Split(" ");//转换成16进制数存储在byte类型数组中
                  byte[] hex = new byte[hexWords.Length];
                                 for (int i = 0; i < hexWords.Length; i++)
                                 {
                                     hex[i] = Convert.ToByte(hexWords[i],16);
                                 }
                                 string ret = System.Text.Encoding.ASCII.GetString(hex);
                                 serialPort.WriteLine(ret);

但不知道为何通过串口助手监测到发下去的是 Data: 5A 3F 05 3F 01 04 00 01 0A
而不是本人想发的:5A A5 05 82 01 04 00 01
讨教问题出在哪里

解决方案

5

A5,不属于ASCII编码范围,因此被换成了问号。
3F == “?”

5

用SerialPort.Write(byte[] buffer, int offset, int count);

10

SerialPort.Write 方法
Write(String) 将指定的字符串写入串行端口。
Write(Byte[], Int32, Int32) 使用缓冲区的数据将指定数量的字节写入串行端口。
Write(Char[], Int32, Int32) 使用缓冲区的数据将指定数量的字符写入串行端口。
不要在一棵树上吊死!
假如一定想要转换成字符串,可以这样
string ret = string.Join(“”, hex.Select(x => (char)x).ToArray());

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c# string 和byte[] 转换问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)