2012-03-16 47 views
1

所以這個傳感器通過返回兩個(高和低)有符號字節返回一個-500-500之間的有符號值。我如何使用這些來確定實際價值是什麼?我知道我需要做2的補充,但我不知道如何。這是我現在有 -從2個16位有符號字節獲取帶符號整數?

real_velocity = temp.values[0]; 
    if(temp.values[1] != -1) 
     real_velocity += temp.values[1]; 

    //if high byte > 1, negative number - take 2's compliment 
    if(temp.values[1] > 1) { 
     real_velocity = ~real_velocity; 
     real_velocity += 1; 
    } 

但它只是返回什麼是積極的負值。例如,-200返回字節255(高)和56(低)。增加了這些311.但是,當我運行上面的代碼它告訴我-311。感謝您的任何幫助。

+1

請指定語言(和搜索第一)。 – 2012-03-16 00:31:59

+0

我已經搜索,但我只找到約1個字節的東西,而不是兩個組合。 – Sterling 2012-03-16 00:33:52

+0

標題說16位字節,但文本暗示8位字節。這是什麼? – 2012-03-16 00:35:23

回答

4
-200 in hex is 0xFF38, 

你得到兩個字節0xFF和0x38, 將這些回十進制你可能認識他們

0xFF = 255, 
0x38 = 56 

你的傳感器沒有返回2個符號字節,但是一個簡單的高和一個有符號的16位數的低字節。

所以你的結果是

value = (highbyte << 8) + lowbyte 

值是16位有符號變量。

0
real_velocity = temp.values[0]; 
real_velocity = real_velocity << 8; 
real_velocity |= temp.values[1]; 
// And, assuming 32-bit integers 
real_velocity <<= 16; 
real_velocity >>= 16; 
0

對於8位字節,第一剛轉換爲unsigned

typedef unsigned char Byte; 
unsigned const u = (Byte(temp.values[1]) << 8) | Byte(temp.values[0]); 

然後,如果比所述上限爲16位二進制補碼值,減去2 :

int const i = int(u >= (1u << 15)? u - (1u << 16) : u); 

你可以在比特級別做技巧,但我不認爲這有什麼意義。

以上假設CHAR_BIT = 8,unsigned大於16位,並且機器和期望的結果是二進制補碼。


#include <iostream> 
using namespace std; 

int main() 
{ 
    typedef unsigned char Byte; 
    struct { char values[2]; } const temp = { 56, 255 }; 

    unsigned const u = (Byte(temp.values[1]) << 8) | Byte(temp.values[0]); 
    int const  i = int(u >= (1u << 15)? u - (1u << 16) : u); 

    cout << i << endl; 
} 
2

根據你給的例子,似乎值已經是2的補數。您只需將高位字節左移8位,並將這些值相加即可。

real_velocity = (short) (temp.values[0] | (temp.values[1] << 8)); 
0

您可以移位並掩碼值。

int main() 
{ 
    char data[2]; 
    data[0] = 0xFF; //high 
    data[1] = 56; //low 
    int value = 0; 

    if (data[0] & 0x80) //sign 
     value = 0xFFFF8000; 

    value |= ((data[0] & 0x7F) << 8) | data[1]; 

    std::cout<<std::hex<<value<<std::endl; 
    std::cout<<std::dec<<value<<std::endl; 
    std::cin.get(); 
} 

輸出:

ffffff38

-200

+0

我不認爲需要額外的遮罩。如果將高位值作爲unsigned char轉換爲unsigned short,然後將低位值轉換爲unsigned char作爲unsigned char,然後將結果重新解釋爲signed short,結果是簽了-200。 – 2012-03-16 01:28:57

相關問題