Byte order in C bit field?

67 Views Asked by At

enter image description here

Consider uint32_t n = 0x12345678; it stores in BE machine or LE machine, like the picture shows; now I have a structure defined like this

struct DATA {
    uint32_t a : 24;
    uint32_t b : 8;
};

int main() {
    struct DATA data;
    data.a = 0x123456;
    data.b = 0x78;
    return 0;
}

How does it store in memory?

1

There are 1 best solutions below

1
chux - Reinstate Monica On

How does it store in memory?

Many possibilities:

  • BE: no padding: 0x12, 0x34, 0x56, 0x78
  • BE: padding to even: 0x12, 0x34, 0x56, ..., 0x78, ...
  • BE: padding to quad: 0x12, 0x34, 0x56, ..., 0x78, ..., ..., ...
  • LE: no padding: 0x56, 0x34, 0x12, 0x78
  • LE: padding to even: 0x56, 0x34, 0x12, ..., 0x78, ...
  • LE: padding to quad: 0x56, 0x34, 0x12, ..., 0x78, ..., ..., ...
  • Other Endians:
  • Invalid as only types int, unsigned, bool well defined for bit-fields.
  • None: as an optimized compile can eliminate the variable as used in the example.
  • ...

Good code should not care how it is stored in memory.
If code really needs a certain order, use an array of uint8_t instead of a bit-field.


Note: many compilers will not store a uint32_t on an odd boundary as in the example.