bit field padding in C

后端 未结 4 551
暗喜
暗喜 2021-02-10 15:06

Continuing my experiments in C, I wanted to see how bit fields are placed in memory. I\'m working on Intel 64 bit machine. Here is my piece of code:

#include <         


        
4条回答
  •  伪装坚强ぢ
    2021-02-10 15:45

    The placement of bit-fields in memory depends not only on how the compiler decides to assign the various fields within the structure but also on the endian-ness of the machine on which you are running. Lets take these one-by-one. The assignment of the fields within the compiler can be controlled by specifying the size of the field (as @DDD) points out, but also through another mechanism. You can tell the compiler to either pack your structure or leave it better suited for how the compiler may want to optimize for the machine architecture for which you are compiling. Packing is specified using the packed type attribute. Thus, if you specify the struct as:

    struct __attribute__ ((__packed__)) box_props {
        ...
    } 
    

    you may well see a different layout in memory. Note that you won't see the layout being different by examing the structure components - its the layout in memory that could change. Packing a structure is crucially important when communicating with something else such as an IO device which expects specific bits at specific places.

    The second issue with bit field structures is their layout dependence on endian-ness. The layout of the struct in memory (or any data for that matter) depends on whether you are running on a big-endian (POWER) or little-endian (e.g., x86) machine. Some systems (e.g., embedded PowerPC systems are bi-endian).

    In general, bit fields make it very hard to port code because you are futzing with the layout of data in memory.

    Hope this helps!

提交回复
热议问题