2013-06-12 340 views
9

我收到一個端口號爲2個字節(最低有效字節在前),我想將其轉換爲一個整數,以便我可以使用它。我做了這個:將2個字節轉換爲整數

char buf[2]; //Where the received bytes are 

char port[2]; 

port[0]=buf[1]; 

port[1]=buf[0]; 

int number=0; 

number = (*((int *)port)); 

但是,有什麼問題,因爲我沒有得到正確的端口號。有任何想法嗎?

+0

是你的字節順序是一樣的嗎? –

+1

也2字節與4字節:短vs int –

+1

使用uint16_t來鑄造 –

回答

18

我收到的2個字節的端口號(至少顯著字節在前)

那麼你可以這樣做:

int number = buf[0] | buf[1] << 8; 
+0

正是,非常感謝! – user1367988

+2

@ user1367988只要在該平臺上簽名'char'即可。 –

3

如果您BUF到unsigned char buf[2],你可以只簡化爲;

number = (buf[1]<<8)+buf[0]; 
3

我明白這個已經合理回答了。然而,另一種技術是在你的代碼中定義一個宏,例如:

// bytes_to_int_example.cpp 
// Output: port = 514 

// I am assuming that the bytes the bytes need to be treated as 0-255 and combined MSB -> LSB 

// This creates a macro in your code that does the conversion and can be tweaked as necessary 
#define bytes_to_u16(MSB,LSB) (((unsigned int) ((unsigned char) MSB)) & 255)<<8 | (((unsigned char) LSB)&255) 
// Note: #define statements do not typically have semi-colons 
#include <stdio.h> 

int main() 
{ 
    char buf[2]; 
    // Fill buf with example numbers 
    buf[0]=2; // (Least significant byte) 
    buf[1]=2; // (Most significant byte) 
    // If endian is other way around swap bytes! 

    unsigned int port=bytes_to_u16(buf[1],buf[0]); 

    printf("port = %u \n",port); 

    return 0; 
}