views:

59

answers:

2

I'm working with a proprietary protocol that transmits integers as 16 bit two's complement in two parts. The LSB is transmitted first followed by the MSB. Is the following code to restore the original value correct?

unsigned char message[BLK_SIZE];
// read LSB to message[0] and MSB to message[1]
short my_int = (message[1] << 8) | message[0];
+1  A: 

I believe that code will fail if short is not 16 bits, so your code may fail on some platforms. You may never find a platform it fails on though.

int16_t, if available on your target platform(s), may be a better choice.

JosephH
Where does int16_t come from? Is that standard c++, c or some POSIX stuff?
Marco
shorts must be at least 16 bits, so the code is OK.
anon
http://linux.die.net/man/3/int16_t
codymanix
I should have been more specific - I believe it would fail for negative values if short is *larger* than 16 bits, which is permitted by the C++ standard.
JosephH
A: 

Your code looks correct, but you could use intrinsic C functions for ensuring that your protocol is truly platform independant:

short my_int = ntohs(*(short*)message)

codymanix
He wants a conversion specific to his own protocol.
anon