I have the following struct
struct header { unsigned int op:16; unsigned int A:1; unsigned int B:1; unsigned int C:1; unsigned int pad:1; } int main() { struct header a; printf("size of header is: %lu\n", sizeof(a)); return 0; } output is size of header is: 4
If I use __attribute__((__packed__))
struct __attribute__((__packed__)) header { unsigned int op:16; unsigned int A:1; unsigned int B:1; unsigned int C:1; unsigned int pad:1; } int main() { struct header a; printf("size of header is: %lu\n", sizeof(a)); return 0; } output is size of header is: 3
Is there a way to avoid the padding to 3 bytes? Can I take only the required 20 bits? One of the reason I need this is for converting the struct to a hex number e.g
struct header test1, test2; test1.op = 1; test1.A = 0; test1.B = 1 test1.C = 0; test1.pad = 0; test2.op = 1024; test2.A = 0; test2.B = 1 test2.C = 1; test2.pad = 0; is converted to 0x20001 and 0x60400 respectively and would like to avoid the need to remove the padding if possible
uint32_t. That's also portable, something bit-fields are not.One of the reason I need this is for converting the struct to a hex numbeI do not understand, how is that a reason?is convertedC does not come with "auto-convert-struct-to-hex" utility. How are you converting the struct into0x20001representation? Please post your code.