0

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

2
  • 1
    If you need a hex number, stop using bit-fields and just use an uint32_t. That's also portable, something bit-fields are not. Commented Feb 27, 2022 at 14:23
  • 1
    Why does it make a difference if you use 20 bits or 24 bits? Why do you care? One of the reason I need this is for converting the struct to a hex numbe I do not understand, how is that a reason? is converted C does not come with "auto-convert-struct-to-hex" utility. How are you converting the struct into 0x20001 representation? Please post your code. Commented Feb 27, 2022 at 14:34

2 Answers 2

2

Is it possible to pack a struct in C to size defined by bits

No.

Is there a way to avoid the padding to 3 bytes?

No.

Can I take only the required 20 bits?

No.

The smallest addressable unit is a byte. Everything in C has to be a multiple of a byte.

(Theoretically, you could use a compiler (or re-compile GCC) with a byte having 10 bits, then your struct would take exactly 2 bytes. That would be tedious, non-portable and I would say ridiculous). However, on any modern platform, a byte has 8 bits.

Sign up to request clarification or add additional context in comments.

Comments

0

C 2018 6.2.6 2 says:

Except for bit-fields, objects are composed of contiguous sequences of one or more bytes,…

Therefore, a structure, which is not a bit-field even if it is composed solely of bit-fields, must be composed of a whole number of bytes.

(A C implementation could extend the C standard by allowing some objects to be a fractional number of bytes, but I am not aware of any C implementation that does this.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.