现在我只给出收发中文数据的示例代码。 通常情况下,我们的程序代码是如下这样: SerialPort serialPort = new SerialPort(); //这是串口通信对象 serialPort.WriteLine("Hello World"); //这是发送数据 string message = serialPort.ReadLine(); //这是接收数据 这没什么问题,收发都正常。但当你把英文"Hello World"换成中文"你好世界" 发送出去后,在另一边接收到的却是乱码。那么,怎样正确收发中文呢?正确的做法是,先将中文字符编码后再发送。接收时,将数据解码还原成中文。具体看下面: //在发送数据时,使用这样的方法代码。 System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); Byte[] writeBytes = utf8.GetBytes("你好世界"); serialPort.Write(writeBytes, 0, writeBytes.Length); //在接收数据时,使用这样的方法代码。 System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(); Byte[] readBytes = new Byte[serialPort.BytesToRead]; serialPort.Read(readBytes, 0, readBytes.Length); String decodedString = utf8.GetString(readBytes); Console.WriteLine(decodedString); //控制台输入了中文:你好世界这样就可以支持收发中文、英文、以其世界上常见的语种文字,毕竟UTF8编码支持大多数语言文字。如果,我们不使用UTF8编码,而使用GB2312编码,可以不可以呢?当然可以了。问题是死的,而头脑是灵活。呵呵~
原创:
在c#中,如果是通过串口要给下位机发送中文编码或给其他软件(如串口调试助手),则最好采用unicode编码,可采用
System.Text.UnicodeEcoding unic= new System.Text.UnicodeEcoding (); Byte[] writeBytes = unic.GetBytes("你好世界");
但是此时获取的编码是低位在前,需要进行高低位互换一下,然后再调用 serialPort.Write(writeBytes, 0, writeBytes.Length);
串口收发中文问题
最新推荐文章于 2024-05-29 11:13:45 发布