0

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
FLYFLY
  • 49
  • 6
  • Related: https://stackoverflow.com/questions/15136426/memory-layout-of-struct-having-bitfields – Jeremy Friesner Aug 09 '23 at 02:56
  • 2
    Per Jeremy Friesner, does it answer your question? [Memory layout of struct having bitfields](https://stackoverflow.com/questions/15136426/memory-layout-of-struct-having-bitfields) – Davis Herring Aug 09 '23 at 03:19
  • 2
    Succinctly — the standard leaves almost all the details about bit-fields up to the implementation. They are implementation-defined; the implementation should document what it does. But the details and nuances depend on your hardware and any ABI that the system enforces. See, for example, C11 [§6.7.2.1 Structure and union specifiers](http://port70.net/~nsz/c/c11/n1570.html#6.7.2.1). – Jonathan Leffler Aug 09 '23 at 05:40
  • If you ask for your specific target and specific compiler, please [edit] your question and add that information. However, in that case you can deduce the memory layout yourself. – the busybee Aug 09 '23 at 06:04

1 Answers1

1

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • The types of bit-field elements usually work so that if there are consecutive bit-fields with the same type and all the fields fit into one storage unit of the type (as in the example — 32 bits fit into a `uint32_t`), then those bit-fields will be stored in the same storage unit. If the type changes, all bets are off — most probably, the bit-fields will be in separate storage units. There's no question of storing a `uint32_t` on an odd boundary; the bit-fields aren't really `uint32_t` anyway (more like `uint24_t` and `uint8_t`, only one of which is a regular type). – Jonathan Leffler Aug 09 '23 at 16:55