views:

90

answers:

1

I got some trouble with bitfields and endian stuff... I confused.

I need to parse some data got from the network, the sent are in lil endian (im using boost::asio)

Can you explain me this

struct TEST
{
 unsigned short _last : 1;
 unsigned short _ID : 6;
 unsigned short _LENGH : 9;

};
struct TEST2
{
 unsigned short _LENGH:9 ;
 unsigned short _ID:6 ;
 unsigned short _last:1 ;
};


int main(int argc, char* argv[])
{
 printf("Hello World!\n");

 TEST one;
 one._ID    = 0;
 one._last  = 0;
 one._LENGH = 2; //the value affected here is always divided by 2, it is multiplied by 2 when i cast a short to this structure

 TEST2 two;
 two._ID   =  0;
 two._last  = 0;
 two._LENGH = 2; //the value here is well stored


 bit_print((char*)&one,2);
 bit_print((char*)&two,2);
 return 0;
}

[OUTPUT]

00000000 00000001

00000010 00000000

+3  A: 

Why are you saying that the second value is "well stored"? Look at your own output: if the first field (_LENGTH) in two is supposed to consist of 9 bits, then the second output is also incorrect. It was supposed to be 00000001 00000000, but instead you got 00000010 00000000, meaning that in two your value got "multiplied" by 2.

I'd guess that your bit_print is broken and prints nonsense.

(Obligatory disclaimer: Bit-field layout is implementation defined. You are not guaranteed anything layout-related in C++ language when you work with bit-fields.)

AndreyT
They are divided by two in both cases. His bit_print is missing the low bit.
Hans Passant
@Hans Passant: I don't see it "divided" by two in the second case. If the 9-bit-long field is supposed to occupy the first 9 bits of the second output, then the value we currently see there is 4, while the stored value is 2. I.e. the value got "multipled" by 2 somehow.
AndreyT
The 2nd byte is 2, not 4 like it should be.
Hans Passant