2013-06-12 15 views
9

Ricevo un numero di porta come 2 byte (il byte meno significativo prima) e voglio convertirlo in un numero intero in modo che possa lavorare con esso. Ho fatto questo:Converti 2 byte in un numero intero

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

Tuttavia, c'è qualcosa di sbagliato perché non ottengo il numero di porta corretto. Qualche idea?

+0

la tua endianità è la stessa? –

+1

anche 2 byte vs 4 byte: short vs int –

+1

usa uint16_t per eseguire il cast –

risposta

18

ricevo un numero di porta come 2 byte (byte meno significativo prima)

È quindi possibile fare questo:

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

Esattamente, grazie mille! – user1367988

+2

@ user1367988 Attenzione solo nel caso in cui 'char' sia firmato su quella piattaforma. –

3

Se fai buf in un unsigned char buf[2], si può solo semplificarlo a;

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

Apprezzo che questo abbia già ricevuto una risposta ragionevole. Tuttavia, un'altra tecnica è quella di definire una macro nel tuo codice, ad esempio:

// 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; 
} 
Problemi correlati