我在 MSVC++ 2008 中定义了以下结构:
struct{
Uint16 XDD;
unsigned XDD_UI:8;
unsigned XDD_CR:8;
}byte;
当对上述结构执行 sizeof 时,它表明 unsigned 使用 32 位来存储数据。
- 这是为什么,它与内存对齐有关吗?
- 我怎么能强制编译器只使用定义的 8 位而不用 触及结构定义?
最佳答案
unsigned
是 unsigned int
的缩写,在 Windows 上是 32 位宽。这意味着它具有 4
的对齐方式。由于您的结构是对齐的,因此在 XDD
和 XDD_UI
之间有两个字节填充,并且在结构末尾有两个字节填充。
你的结构是这样布局的:
0-1 XDD 2-3 <padding> 4-4 XDD_UI 5-5 XDD_CR 6-7 <padding>
If you want the struct to be packed then you need to pack it. Use #pragma pack
to achieve that. However, even if you do that, the compiler produces a struct with size 6. That's because the bitfields are packed into an unsigned int
and so your two bitfields will always consume 4 bytes.
If you made sure that your bitfields were declared as being of a type whose size was no larger than 2 bytes, then your struct would be 4 bytes. And that would be true for an aligned struct. For instance, this struct has size 4.
struct s {
unsigned short XDD;
unsigned short XDD_UI:8;
unsigned short XDD_CR:8;
};
但是,在我看来,声明没有位域的结构更明智:
struct s {
Uint16 XDD;
unsigned char XDD_UI;
unsigned char XDD_CR;
};
您可以声明该结构对齐并具有您想要的布局。
关于c++ - 为什么 "unsigned"映射到 MSVC C++ 中的 32 位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22010210/