简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM