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

Time:02-28

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

CodePudding user response:

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.

CodePudding user response:

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.)

  • Related