The size of the structure of the bit field in C

I have a representation of the IP header in C with bit-precision fields:

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 for 2 bytes. So why is the size of the structure ( sizeof(ipv4_fragmenting)) equal to 4 instead of 2?

My compiler: GCC 4.8.1

Edit:

If bitpods are so platform specific and a packed attribute is unreliable, then what would be the right solution for representing elements of previously defined protocols such as IPv4?

+3
source share
4 answers

Saving a bit field is implementation dependent. The fields that you define can be supplemented (increase the required storage).

+1
source

, , .

4 GCC 4.8.1 ( 32- ); , , GCC 4.8.1. SO , packed , . #pragma pack. :

#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));
}

3 , ILP32 MinGW GCC 4.8.1.

+1

On some 32-bit platforms, structures are populated at 32-bit boundaries, for example. every 4 bytes. In GCC, I think you can control this on some platforms: Pragma package structure

0
source

I always read that sizes of sizes depend on implementation and architecture and OS. I do not think this is a mistake. In any case, you should trust your function sizeof, as this will tell you your specific truth.

0
source

All Articles