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
holathatsizeof(hola)prints 1? In C99, the format used to printsize_tshould be%02zX; in C89, there isn't a reliable way to handle it (which is why thezmodifier was added in C99), but you could cast the result ofsizeof(hola)tointsince%02Xexpects to print anint. On a big-endian 64-bit machine, you might well get zero printed as the size.