Memory layout of struct having bitfields

后端 未结 6 1875
日久生厌
日久生厌 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:00

    I agree with what unwind said. Bit fields are compiler dependent.

    If you need the bits to be in a specific order, pack the data into a pointer to a character array. Increment the buffer the size of the element being packed. Pack the next element.

    pack( char** buffer )
    {
       if ( buffer & *buffer )
       {
         //pack ver
         //assign first 4 bits to 4. 
         *((UInt4*) *buffer ) = 4;
         *buffer += sizeof(UInt4); 
    
         //assign next 4 bits to 5
         *((UInt4*) *buffer ) = 5;
         *buffer += sizeof(UInt4); 
    
         ... continue packing
       }
    }
    

提交回复
热议问题