I have one device which gives data in non printable characters through serial port. I am converting the data to Hex by using Encoding(to get byte array of data) and then BitConverter.ToString()(to get the Hex String). But I am getting different hex value for the same data in Real Term(TCP Terminal). I need the value which is coming in Real Term. How do I do? Ex: Data - "\t\0î\0\0\u0098$VeW", My hex- 0900EE00003F24566557, In Real Term - 0900EE00009824566557. I have tried all types of Encoding. Code:-
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(10);
string recievedData = port.ReadExisting();
}
The problem is that you're trying to read binary data as if it's text. Don't use the ReadExisting()
call - use Read(byte[], int, int)
:
public void HandleDataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[port.BytesToRead];
int bytesRead = port.Read(data, 0, data.Length);
if (bytesRead != data.Length)
{
throw new IOException("Unable to read advertised number of bytes");
}
}
See more on this question at Stackoverflow