c++ - 为什么 "unsigned"映射到 MSVC C++ 中的 32 位?

标签 c++ visual-c++ visual-studio-2008 struct unsigned

我在 MSVC++ 2008 中定义了以下结构:

struct{
 Uint16  XDD;
 unsigned XDD_UI:8;
 unsigned XDD_CR:8;
}byte;

当对上述结构执行 sizeof 时,它表明 unsigned 使用 32 位来存储数据。

  • 这是为什么,它与内存对齐有关吗?
  • 我怎么能强制编译器只使用定义的 8 位而不用 触及结构定义?

最佳答案

unsignedunsigned int 的缩写,在 Windows 上是 32 位宽。这意味着它具有 4 的对齐方式。由于您的结构是对齐的,因此在 XDDXDD_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/

相关文章:

C++ 将字符串解析为具有特定类的整数

c++ - 带有 C++11 的 Visual Studio 2008

vb.net - 无法在Visual Studio中进行调试

c - 如何使格式文档快捷方式适用于 Visual Studio 2008 中的 C 源文件?

c++ - 如何从 QGraphicsView 中检索选定区域?

c++ - 如何在 C++ 中获取不同行的 .csv 文件?

visual-studio - Microsoft Visual Studio : opendir() and readdir(), 怎么办?

c++ - 如何修复 Microsoft typeinfo.name() 内存泄漏?

visual-studio-2008 - 有状态的 WCF Web 服务

c++ - 计算字符串中所有字符的函数 - C++