Memory layout of struct having bitfields

后端 未结 6 1881
日久生厌
日久生厌 2020-12-03 15:27

I have this C struct: (representing an IP datagram)

struct ip_dgram
{
    unsigned int ver   : 4;
    unsigned int hlen  : 4;
    unsigned int stype : 8;
            


        
6条回答
  •  难免孤独
    2020-12-03 16:17

    No, bitfields are not good for this purpose. The layout is compiler-dependant.

    It's generally not a good idea to use bitfields for data where you want to control the resulting layout, unless you have (compiler-specific) means, such as #pragmas, to do so.

    The best way is probably to implement this without bitfields, i.e. by doing the needed bitwise operations yourself. This is annoying, but way easier than somehow digging up a way to fix this. Also, it's platform-independent.

    Define the header as just an array of 16-bit words, and then you can compute the checksum easily enough.

提交回复
热议问题