Why bit endianness is an issue in bitfields?

后端 未结 7 1998
忘了有多久
忘了有多久 2020-11-22 03:12

Any portable code that uses bitfields seems to distinguish between little- and big-endian platforms. See the declaration of struct iphdr in linux kernel for an example of su

7条回答
  •  广开言路
    2020-11-22 04:14

    Bit field accesses are implemented in terms of operations on the underlying type. In the example, unsigned int. So if you have something like:

    struct x {
        unsigned int a : 4;
        unsigned int b : 8;
        unsigned int c : 4;
    };
    

    When you access field b, the compiler accesses an entire unsigned int and then shifts and masks the appropriate bit range. (Well, it doesn't have to, but we can pretend that it does.)

    On big endian, layout will be something like this (most significant bit first):

    AAAABBBB BBBBCCCC
    

    On little endian, layout will be like this:

    BBBBAAAA CCCCBBBB
    

    If you want to access the big endian layout from little endian or vice versa, you'll have to do some extra work. This increase in portability has a performance penalty, and since struct layout is already non-portable, language implementors went with the faster version.

    This makes a lot of assumptions. Also note that sizeof(struct x) == 4 on most platforms.

提交回复
热议问题