2013-06-12 15 views
9

Ich empfange eine Portnummer als 2 Bytes (am wenigsten signifikante Byte zuerst) und ich möchte es in eine ganze Zahl umwandeln, damit ich damit arbeiten kann. Ich habe das gemacht:Convert 2 Bytes in eine ganze Zahl

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)); 

Allerdings ist etwas falsch, weil ich nicht die richtige Portnummer bekomme. Irgendwelche Ideen?

+0

ist Ihre Endianz die gleiche? –

+1

auch 2 Bytes vs 4 Bytes: kurze vs int –

+1

Verwenden Sie Uint16_t, um die Besetzung zu tun –

Antwort

18

Ich erhalte eine Portnummer als 2 Bytes (niedrigstwertiges Byte zuerst)

Sie können dies dann tun:

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

Genau, vielen Dank! – user1367988

+2

@ user1367988 Vorsicht nur, wenn 'char' auf dieser Plattform signiert ist. –

3

Wenn Sie buf in ein unsigned char buf[2] machen, könnten Sie einfach vereinfachen Sie es zu;

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

Ich weiß, das wurde bereits vernünftig beantwortet. Eine andere Technik ist jedoch, ein Makro in Ihrem Code zu definieren, zB:

// 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; 
} 
Verwandte Themen