sizeof pragma 打包位域结构数组 [英] sizeof pragma packed bitfield struct array

查看:33
本文介绍了sizeof pragma 打包位域结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Visual Studio 2013 用于 x64 系统.我有以下结构:

I use Visual Studio 2013 for a x64 system. I have the following struct:

#pragma pack(1)
    struct TimeStruct
    {
      int milliseconds  : 10;
      BYTE seconds      : 6;    
      BYTE minutes      : 6;    
      BYTE hour         : 5;    
      BYTE day          : 5;    
    };
#pragma pack()

和一个数组:

TimeStruct stArray[10];

当我使用 sizeof(stArray);我得到 80 而不是 40.

When I use sizeof(stArray);I get 80 as a resault instead of 40.

我需要知道问题是编译器没有正确打包还是 sizeof 没有考虑位域的实际大小.

I need to know if the problem is that the compiler doesn't pack correctly or if sizeof doesn't consider the bitfield's actual size.

谢谢

推荐答案

参见 VC++ 在打包位域时在做什么? 有关 MSVC 如何处理位域的更多说明.

See What is VC++ doing when packing bitfields? for more explanation on how MSVC treats bitfields.

它的实现取决于位域的打包和排序方式,因此请注意布局可能与您期望的不同,并且取决于您使用的特定编译器.

It's implementation dependent how bitfields are packed and ordered, so be aware that the layout can be different from what you expect, and will depend on the particular compiler you are using.

sizeof() 为您提供结构的大小,而不管其成员是什么,因此位域打包与您的期望不同.

sizeof() gives you the size of the struct regardless of what its members are, so it's the bitfield packing that's different from your expectations.

您可以从 文档 中推测布局,或者使用此代码凭经验发现布局:

You can possibly rason about the layout from the documentation or use this code to empirically discover the layout:

struct TimeStruct a;
unsigned char *b = (unsigned char*)&a;
a.milliseconds = 1;
a.seconds = 2;
a.minutes = 3;
a.hour = 3;
a.day = 4;
for(size_t i = 0; i < sizeof a; i++)
  printf("%02X ", b[i]);

 -> 64 bit compiler 01 00 00 00 02 03 04 05
 -> 32 bit compiler 01 30 FE 00 02 03 A4 65

看起来结构体被分配了一个完整的 int 为 1. int milliseconds : 10; 成员,剩下的 3 个字节在此之后被单独打包,为每个成员分配一个 BYTE,但不是组合来自不同分配单元的位.

It appears the struct is allocated an entire int for the 1. int milliseconds : 10; member, and the remaining 3 bytes are packed individually after that, allocating a BYTE for each member, but not combining bits from the different allocated units.

如果对所有字段使用 int 或 unsigned int,您应该能够使用 MSVC 编译器将其紧密打包,并且此结构将占用 4 个字节:

You should be able to pack it tightly with the MSVC compiler if you use int or unsigned int for all the fields, and this struct will take 4 bytes:

struct TimeStruct
{
  int milliseconds : 10;
  int seconds      : 6;    
  int minutes      : 6;    
  int hour         : 5;    
  int day          : 5;    
};

这篇关于sizeof pragma 打包位域结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆