2017-09-23 82 views
0

我正在写一个C#应用程序,它将从3个不同的COM端口接收串行数据,配置8位UART,无奇偶校验。其他设备将发送和接收二进制编码的HEX ex。 AF01h = 10101010 00000001每个字节两个字符。我设置了虚拟COM端口和一个用于测试目的的简单应用程序,并且在我连接设备之前来回发送数据。我发现数据在发送和接收时默认为ASCII编码,但我需要二进制编码HEX。我没有在编码类中看到该选项,并且不希望该应用程序使用与其他3个设备完全不同的编码。现在,我使用这个代码将字符串转换时,它被送到null或十六进制串行端口编码

string binarystring = String.Join(String.Empty, hexstring.Select(c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0'))); 
sport.Write(binarystring); 
txtReceive.AppendText("[" + dtn + "] " + "Sent: " + binarystring + "\n"); 

这适用于测试传输现在,但我最终将改变代码直接放置两位数的十六进制数字转换为字节数组。

此代码将允许我输入AF01h = 1010101000000001,但在应用程序的接收端,我获得16个字节的ASCII编码字符。有没有一种方法可以将应用程序与其他设备放在同一页面上?

+0

不要使用Write(string)过载。使用byte []来确保正确编码二进制数据。 –

+0

在我将它们移动到Byte []之前,我不得不从文本框中对ASCII字符进行编码?一旦我发送字节,ASCII编码/解码是否仍然适用? –

回答

0

想出了一个办法。只需要十六进制的长字符串转换为两个十六进制字符字节整数

string hex = txtDatatoSend.Text; //"F1AAAF1234BA01" 
int numOfBytes = HEX.Length; 
byte[] outbuffer = new byte[numOfBytes/2]; 
for (int i = 0; i < numOfBytes; i += 2) 
{ 
outbuffer[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); 
} 
sport.Write(outbuffer, 0, outbuffer.Length); 
sport.DiscardOutBuffer() 

唯一需要注意的是你必须在偶数字符

在另一端的输入数据被正确放置回到Byte []中,我可以像这样解码它。

byte[] inbuffer = new byte[sport.BytesToRead]; 
sport.Read(inbuffer, 0, inbuffer.Length); 
txtReceive.AppendText("[" + dtn + "] " + "Received: " + inbuffer.Length + " bytes "); 
for (int i = 0; i < inbuffer.Length; i++) 
{ 
string hexValue = inbuffer[i].ToString("X2"); 
txtReceive.AppendText(inbuffer[i] + " is " + hexValue + "HEX "); 
} 
txtReceive.AppendText("\n"); 
sport.DiscardInBuffer();