2013-01-09 71 views
1

我有一種感覺,這與BitConverter.ToUInt16 wiorks的方式,但我不能爲我的生活弄清楚爲什麼這是給我時髦的數據。爲什麼這不會取消兩個最重要的位?

我需要忽略進入端口的前兩位,並將其餘位轉換爲16位無符號整數。

我已經嘗試顛倒數組,顛倒我的面具,做了兩個,不同的轉換和各種奇怪的事情。

進來的兩個字節是第一個是最重要的。第一個字節的前兩位需要取消設置。

有人能指出我正確的方向嗎?

byte[] buffer = new byte[2]; 
int count = port.Read(buffer, 0, buffer.Length); 

Console.WriteLine("0: {0}", BitConverter.ToString(buffer)); 

ushort value = BitConverter.ToUInt16(buffer, 0); 

Console.WriteLine("1: {0}", value); 

value = (ushort)(value & 0x3FFF); 

Console.WriteLine("2: {0}", value); 

下面是使用BitConverter.ToUInt16然後AND運算與0x3FFF掩模當某些樣本數據。

0: 80-00 
1: 128 
2: 128 <-- this should be 0 

0: 80-00 
1: 128 
2: 128 <-- should be 0 

0: 01-00 
1: 1 
2: 1 <-- should be 1, as it is 

0: 80-00 
1: 128 
2: 128 <-- should be 0 

0: 80-00 
1: 128 
2: 128 <-- should be 0 

逆轉陣列使我的數據是這樣的:

0: 00-01 
1: 256 
2: 256 <-- should be 1 

0: 01-80 
1: 32769 
2: 1 <- not sure what this should be, probably 1 though 
+0

你最終在'value'中做了什麼? – DWright

+0

@DWright我將它添加到問題中,謝謝。 –

回答

0

這樣,人們就擁有了完整的代碼,用於讀取和轉換14位無符號大端整數的串口。

private static void OnDataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort port = sender as SerialPort; 
    if (port.BytesToRead < sizeof(ushort)) 
    { 
     return; 
    } 

    byte[] buffer = new byte[2]; 
    int count = port.Read(buffer, 0, buffer.Length); 

    ushort value = (ushort)(((buffer[0] << 8) | buffer[1]) & 0x3FFF); 
    Console.WriteLine(value); 
} 
1

該進來的兩個字節是與第一個是最顯著。

這就是問題所在。 BitConverter.ToUInt16將第一個字節視爲最不重要的,因爲這就是您的系統的工作原理。見BitConverter.IsLittleEndian

我試圖扭轉陣列,

這應該工作。或者,手動組合這兩個字節,而不使用BitConverter

+0

我試着手動組合這兩個字節,先採用第一種方法,然後左移8,然後對第二種進行ORing,然後應用掩碼。面罩是否正確? –

+0

是的,這對我來說是正確的。 「0x3FFF」的位設置爲0-13,位14和15清零,因此清零最高2位。 – hvd

+0

所以我現在只是做我在我的第一個評論中解釋你的答案。我收到了一些正確的結果,其他的不正確。特別是當設備發送'1'時,我收到'80-01',當設備發送我認爲是'2'的信號時,我收到'02-00'。任何想法爲什麼我的掩飾不適當地計算值? –

相關問題