简体   繁体   English

具有位域的奇数大小的结构

[英]odd sized structure with bitfields

I am trying to fit a few bitfields into a 3-byte struct 我正在尝试将一些位字段放入3字节结构中

#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. 但是,尽管所有位的总和为24,但DSTEntry的sizeof始终为5。我使用的是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. 这对我来说是3号,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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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