两个4位位域不等于一个字节的大小 - 如何修复?

问题描述 投票:3回答:1

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

c++ visual-c++
1个回答
7
投票

使用unsigned char而不是unsigned int

struct X {
    unsigned char type : 4;
    unsigned char tag : 4;
};

static_assert(sizeof(X)==1);
© www.soinside.com 2019 - 2024. All rights reserved.