I don’t know why but the bit fields assignment is not working as expected. Probably is just an stupid thing, but I’ve not been able to locate the problem.
Any help is more than welcome.
typedef struct a {
unsigned char a1 :1;
unsigned char a2 :3;
unsigned char a3 :2;
unsigned char a4 :2;
} __attribute__((packed)) mystruct;
int main() {
mystruct d;
d.a1 = 0;
d.a2 = 2;
d.a3 = 1;
d.a4 = 2;
unsigned char *val = (unsigned char*) &d;
printf("%02X \n", *val);
printf("%02X \n", sizeof(hola));
exit(0);
}
returned output:
94
01
expected output:
26
01
Nearly everything about bit-fields is implementation defined. And particularly the order of bits in a unit.
On your implementation, the bits are stored in a unit lsb (least significant bit) first and not msb (most significant bit) first as you would expect.
What you have is:
which is
0x94if you consider the left most bit is the least significant bit.