abdullah cinar
abdullah cinar

Reputation: 543

Size of a struct containing bitfields defined with different types

I have a struct that contains bitfields with different sizes. Some of the bitfields are only 1 bit and some of them are 32 bit wide. I will fill this struct with a buffer received from a serial communication. So I planned to define them in bitfields then use memcpy to fill the buffer with the received packet.

This is my struct definition:

#pragma pack(push,1)
typedef struct{

    uint32_t    variable1;          //32 bit
    uint16_t    variable2:16;       //16 bit
    uint32_t    variable3:18;       //18 bit
    uint32_t    variable4:10;       //10 bit
    uint32_t    variable5:4;        //4 bit
    uint8_t     variable6;          //8 bit
    uint8_t     variable7:7;        //7 bit
    uint8_t     variable8:1;        //1 bit
    uint8_t     variable9:6;        //6 bit
    uint8_t     variable10:6;       //6 bit
    uint8_t     variable11:7;       //7 bit
    uint8_t     variable12:5;       //5 bit

}error_driver_t;            //Total length should be 15 bytes (120 bit)
#pragma pack(pop)

printf("\r\nSize of error_driver_t: %d\r\n\r\n", sizeof(demoErrorDriver));    //Expected 15, Resulted 20

The serial packet is 15 bytes so I expect this struct to be 15 bytes long too to use the memcpy properly. But when I get the sizeof(error_driver_t), I get 20.

I'm confused about how to use the bitfields when I have both small and bigger types in the same struct.

Upvotes: 1

Views: 215

Answers (1)

John Doe
John Doe

Reputation: 1869

You can't be certain that a struct will have the exact sizeof equal to the sum of the size of the variables contained in it. This is influenced by many factors including struct padding, what pragma pack you are using, which compiler you are using and even in which order your variables are in the struct as stated in this answer to a similar question.

In addition to this the C standard says that:

Multiple adjacent bit fields are usually packed together (although this behavior is implementation-defined)

So you can't be certain that two different variables will occupy exactly the sum of their bitfields either.

All in all your best best would be to use multiple bitmasks and/or bit shifts to get the values you need from the packet.

Upvotes: 1

Related Questions