两个 4 位位字段加起来不等于一个字节的大小 - 如何修复?

Two 4-bit bitfields don't add up to size of one byte - how to fix?

本文关键字:字节 何修复 一个 字段 起来 不等于 两个      更新时间:2023-10-16

我尝试将库从 linux 移植到 win32,有一个结构定义为:

struct X {
    unsigned int    type : 4;
    unsigned int    tag : 4;
}__attribute__((packed));

大小应该是1,我把它改成:

#pragma pack(push, 1)
struct X {
    unsigned int    type : 4;
    unsigned int    tag : 4;
};
#pragma pack(pop)

但是 sizeof(X( 它仍然是 4,编码会搞砸,我怎样才能将大小更改为 1?

使用 unsigned char 而不是 unsigned int

struct X {
    unsigned char type : 4;
    unsigned char tag : 4;
};
static_assert(sizeof(X)==1);