Random Profile
Random Profile

Reputation: 21

odd sized structure with bitfields

I am trying to fit a few bitfields into a 3-byte struct

#pragma pack(push, 1)
typedef struct  _DSTEntry {
    uint8_t reserved :6;
    uint8_t startMonth:4;
    uint8_t startDay:5;
    uint8_t endMonth:4;
    uint8_t endDay:5;
} __attribute__((packed)) DSTEntry;
#pragma pop

However, sizeof DSTEntry is always 5, allthough the sum of all bits is 24. I am using gcc 5.3.0.

Upvotes: 0

Views: 432

Answers (1)

SGeorgiades
SGeorgiades

Reputation: 1821

If you have the freedom to rearrange the elements in the structure, you can try this:

typedef struct  _DSTEntry {
    uint16_t reserved :6;
    uint16_t startDay:5;
    uint16_t endDay:5;
    uint8_t startMonth:4;
    uint8_t endMonth:4;
} __attribute__((packed)) DSTEntry;

This resulted in size 3 for me, with gcc 4.9.2. If the fields must remain in that order, then I think the best you can do is four bytes with:

typedef struct  _DSTEntry {
    uint16_t reserved :6;
    uint16_t startDay:5;
    uint16_t startMonth:4;
    uint8_t endDay:5;
    uint8_t endMonth:4;
} __attribute__((packed)) DSTEntry;

Upvotes: 0

Related Questions