简体   繁体   English

C中位域结构的大小

[英]Size of bit-field struct in C

I have a representation of an IP header in C with bit-precision fields: 我在C中使用位精度字段表示IP头:

typedef struct __attribute__((packed)) {
    unsigned char __reserved : 1;
    unsigned char dont_fragment : 1;
    unsigned char more_fragment : 1;
    unsigned short fragment_offset : 13; // if fragmented, in 8 byte units from the start of the datagram
} ipv4_fragmenting;

I use 16 bits that can be stored on 2 bytes. 我使用16位,可以存储在2个字节上。 So why is the size of the structure ( sizeof(ipv4_fragmenting) ) is 4 instead of 2? 那么为什么结构的大小( sizeof(ipv4_fragmenting) )是4而不是2?

My compiler: GCC 4.8.1 我的编译器:GCC 4.8.1

Edit: 编辑:

If bitfields are so platform-specific and packed attribute is unreliable what would be the correct solution to represent elements of previously defined protocols like IPv4? 如果位域特定于平台且打包属性不可靠,那么表示先前定义的协议(如IPv4)的元素的正确解决方案是什么?

Like I've already commented, speculating on bit field and structure size is moot since the language doesn't mandate anything in this area. 就像我已经评论过的那样,对比特字段和结构大小的推测是没有实际意义的,因为该语言并没有强制要求这个领域。

As for the size being 4 on GCC 4.8.1 (assuming a 32-bit compiler); 至于GCC 4.8.1上的大小为4 (假设是32位编译器); this is perhaps a bug on GCC 4.8.1. 这可能是GCC 4.8.1的一个错误。 I've raised a question on SO previously where setting the packed attribute doesn't work as expected, like here. 我之前在SO上提出了一个问题,其中设置packed属性不能按预期工作,就像这里一样。 For a byte aligned packing only using #pragma pack works. 对于仅使用#pragma pack工作的字节对齐打包。 Example: 例:

#include <stdio.h>

#pragma pack(push, 1)
typedef struct {
    unsigned char __reserved : 1;
    unsigned char dont_fragment : 1;
    unsigned char more_fragment : 1;
    unsigned short fragment_offset : 13; // if fragmented, in 8 byte units from the start of the datagram
} ipv4_fragmenting;
#pragma pack(pop)

int main()
{
    printf("%u\n", sizeof(ipv4_fragmenting));
}

This prints 3 for me, as expected on a ILP32 machine MinGW GCC 4.8.1. 这对我来说打印3 ,正如在ILP32机器MinGW GCC 4.8.1上预期的那样。

Bit field storage is implementation dependent. 位字段存储取决于实现。 The fields that you have defined may be padded (increasing the storage required). 您定义的字段可以填充(增加所需的存储空间)。

On some 32bit platforms structures are padded to be on 32 bit boundaries, eg. 在某些32位平台上,结构被填充为32位边界,例如。 every 4 bytes. 每4个字节。 On GCC I think you can control this on some platforms see: Structure Packing Pragmas 在GCC上我认为你可以在某些平台上控制这一点,参见: Structure Packing Pragmas

I've always read that type sizes depends on the implementation and architecture and the OS. 我一直在读类型大小取决于实现和架构以及操作系统。 I don't think it's a bug. 我不认为这是一个错误。 Anyway, you must trust on your sizeof function, as this will tell you your particular truth. 无论如何,你必须相信你的sizeof功能,因为这会告诉你你的具体事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM