gpt4 book ai didi

c++ - 两个 4 位位域加起来不等于一个字节的大小 - 如何解决?

转载 作者:太空狗 更新时间:2023-10-29 20:08:14 25 4
gpt4 key购买 nike

我尝试将一个库从 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);

关于c++ - 两个 4 位位域加起来不等于一个字节的大小 - 如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com