为什么使用24位整数时结构的大小不会改变 [英] why size of structure does not change when use 24 bit integer

查看:342
本文介绍了为什么使用24位整数时结构的大小不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Windows平台中端口嵌入代码。
我遇到了下面的问题我在这里发布一个示例代码。
在这里,即使我使用int24大小仍然在窗口中12字节为什么?

I am trying to port embed code in windows platform. I have come across below problem I am posting a sample code here. here even after I use int24 size remains 12 bytes in windows why ?

struct INT24
{
    INT32 data : 24;
};

struct myStruct
{
    INT32 a;
    INT32 b;
    INT24 c;
};

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned char myArr[11] = { 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0xFF,0xFF,0xFF };
    myStruct *p = (myStruct*)myArr;
    cout << sizeof(*p);
}


推荐答案


  • 假设 INT32 的大小为4字节。 INT24 的大小也是4个字节,因为它包含一个 INT32 位字段。由于 myStruct 包含3个大小为4的成员,因此其大小必须至少为12。

  • 大概对齐要求 INT32 的大小为4.因此,即使 INT24 的大小为3, myStruct 仍然必须是12,因为它必须至少具有 INT32 的对齐要求,因此 myStruct 必须填入最接近的4的倍数。

  • Presumably the size of INT32 is 4 bytes. The size of INT24 is also 4 bytes, because it contains a INT32 bit field. Since, myStruct contains 3 members of size 4, its size must therefore be at least 12.
  • Presumably the alignment requirement of INT32 is 4. So, even if the size of INT24 were 3, the size of myStruct would still have to be 12, because it must have at least the alignment requirement of INT32 and therefore the size of myStruct must be padded to the nearest multiple of 4.

any way or workaround ?

这是实现特定的,但下面的hack可能适用于某些编译器/ cpu组合。有关类似功能的语法,请参阅编译器手册,以及目标cpu的手册是否支持未对齐的内存访问。还要意识到,未对齐的内存访问确实有性能损失。

This is implementation specific, but the following hack may work for some compilers/cpu combinations. See the manual of your compiler for the syntax for similar feature, and the manual for your target cpu whether it supports unaligned memory access. Also do realize that unaligned memory access does have a performance penalty.

#pragma pack(push, 1)
struct INT24
{
 INT32 data : 24;
};
#pragma pack(pop)

#pragma pack(push, 1)
struct myStruct
{
INT32 a;
INT32 b;
INT24 c;
};
#pragma pack(pop)

打包位字段可能不会编译器。请务必检查您的行为。

Packing a bit field might not work the same in all compilers. Be sure to check how yours behaves.

我认为标准兼容的方式是存储大小为3和4的字符数组,并且每当需要读取或写入一个整数,你必须 std :: memcpy 的值。这将是一个有点负担实施,也可能比#pragma pack黑客。

I think that a standard compliant way would be to store char arrays of sizes 3 and 4, and whenever you need to read or write one of the integer, you'd have to std::memcpy the value. That would be a bit burdensome to implement and possibly also slower than the #pragma pack hack.

这篇关于为什么使用24位整数时结构的大小不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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