2017-04-12 51 views
0

我有一臺設備通過串口爲非可打印字符提供數據。我通過使用Encoding(獲取數據的字節數組)將數據轉換爲Hex,然後使用BitConverter.ToString()(獲取十六進制字符串)。但是我在Real Term(TCP Terminal)中獲得了相同數據的不同十六進制值。我需要實際價值。我該怎麼做? 例如:數據 - 「\ t \ 0 \ 0 \ 0 \ u0098 $ VeW」, 我的十六進制 - 0900EE00003F24566557, 實際 - 0900EE00009824566557。 我試過所有類型的編碼。 代碼: -獲取不同的十六進制值

public void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    Thread.Sleep(10); 
    string recievedData = port.ReadExisting(); 
} 
+0

這聽起來像你應該從串口讀取數據的二進制開始。您正在使用哪種API,您確定它沒有讀取原始字節的方法嗎? –

+0

我正在通過串行端口的DataReceived事件接收數據,並以字符串形式獲取數據。 – mahua

+0

請顯示代碼 - 「DataReceived」事件似乎實際上並沒有給你本身的字符串。任何阻止你使用'Read(byte [],int,int)'方法的東西?如果你在問題中包含你的代碼,它會更容易幫助你... –

回答

0

的問題是,你想讀的二進制數據,如果是文本。不要使用ReadExisting()呼叫 - 使用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"); 
    } 
}