Why is the order of bit fields in the bytes of structs not defined by the language itself?

送分小仙女□ 提交于 2019-12-11 16:05:20

问题


I came across a problem today where I discovered the way the bit fields in my bytes are ordered is dependent on the endianness of my processor. Take the next example:

struct S {
    uint8_t a : 3;
    uint8_t b : 5;
};

This struct takes one byte but the bit layout depends on the machine:

  • Little endian: b4 b3 b2 b1 b0 a2 a1 a0
  • Big endian: a2 a1 a0 b4 b3 b2 b1

So on a little endian machine it starts filling from the LSB and on a big endian machine it start filling from the MSB. I once heard Stroustrup say it's a main goal to achieve portability across platforms but leaving some things like this is not portable at all. If I were to send this struct over a connection to someone, how would he know which bits mapped to which fields in the struct? Would it not have been easier if the order was fixed? What's the reasoning behind the choice of leaving this open to the processor and compiler? The only safe option is to use bit shifts and masks which uses a lot more code. It would have been so much easier if me and my co-workers could have counted on a fixed order, the little endian way for example, but there certainly must have been a reason why chose not to do it.


回答1:


They're not defined by the language so that it can accommodate the exact situation you've discovered. For bit fields in a byte it makes no difference, but bit fields can occupy larger integer types. Consider this example:

struct bf
{
    uint16_t a : 5;
    uint16_t b : 11;
};

In order for the bits of a field to be adjacent in memory, the bits in a byte must be laid out differently depending on the endianness of the processor.

Big endian:

aaaaabbb bbbbbbbb

Little endian:

bbbbbbbb bbbaaaaa


来源:https://stackoverflow.com/questions/47584050/why-is-the-order-of-bit-fields-in-the-bytes-of-structs-not-defined-by-the-langua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!