Question

I have the following union and it works correct:

#pragma pack(1)
...
union
{
    uint8_t opcode;
    struct
    {
        uint8_t z : 3;
        uint8_t y : 3;
        uint8_t x : 2;
    };
}opcode;    

The size of the union is exactly one byte, according to

printf ("%zu\n", sizeof opcode);  

The problem takes place when I try to make a union from the bit-field there:

union
{
    uint8_t opcode;
    struct
    {
        uint8_t z : 3;
        union
        {
            uint8_t y : 3;
            struct
            {
                uint8_t p : 2;
                uint8_t q : 1;
            };
        }y;
        uint8_t x : 2;
    };
}opcode;    

The result of

printf ("%zu\n", sizeof opcode);  

is 3 bytes. Of course I can workaround this with macros but it is it possible at all?

Was it helpful?

Solution 2

No, it isn't possible to have structs that are fractions of a byte big.

Rationale:

It must be possible to make a pointer to a struct, and the smallest adressable unit is 1 byte.

Note: This limitation exists in all compilers that I know. I don't know whether it is actually mandated by the C standard.

OTHER TIPS

Your code will declare a 3 byte data structure because, as Klas pointed out already, a struct is always padded to the smallest addressable unit.

But it is possible to do what you want by embedding multiple top-level structs in the union and adding padding whenever necessary:

union {
    uint8_t opcode;
    struct {
        uint8_t z:3;
        uint8_t y:3;
        uint8_t x:2;
    };
    struct {
        uint8_t:3;
        uint8_t p:2;
        uint8_t q:1;
    };
} opcode;

Note that it is possible to declare bit-fields without a name for padding. This is a standard C language feature.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top