Byte Order and Bit Order

From Software Engineers Wiki
Jump to: navigation, search

How bit order differs depending on byte order of system?

Answer

Bit allocation is architecture and compiler dependent. However, there is a usual practice.

When bit fields are used in structures, bit allocation differs based on the byte ordering. Assuming 32-bit system,

  • little-endian: bit fields are allocated from LSB (bit 0) to MSB (bit 31)
  • big-endian: bit fields are allocated from MSB (bit 31) to LSB (bit 0)

For example,

#include <stdio.h>
#include <stdint.h>

struct my_bitfield {
        uint32_t nibble0 : 4;
        uint32_t nibble1 : 4;
        uint32_t nibble2 : 4;
        uint32_t nibble3 : 4;
        uint32_t nibble4 : 4;
        uint32_t nibble5 : 4;
        uint32_t nibble6 : 4;
        uint32_t nibble7 : 4;
};

union my_bitfield_union {
        struct my_bitfield fields;
        uint8_t data8[4];
        uint32_t data32;
};

int main(void)
{
        union my_bitfield_union v;

        v.data32 = 0x12345678;

        printf("32bit: %08x\n", v.data32);
        printf("8 bits: %02x %02x %02x %02x\n",
                v.data8[0], v.data8[1], v.data8[2], v.data8[3]);
        printf("4 bit: %x %x %x %x %x %x %x %x\n",
                v.fields.nibble0, v.fields.nibble1, v.fields.nibble2, v.fields.nibble3,
                v.fields.nibble4, v.fields.nibble5, v.fields.nibble6, v.fields.nibble7);

        return 0;
}

On a little-endian system, the bit allocation is as follow.

  • nibble0: bit[3:0]
  • nibble1: bit[7:4]
  • ......
  • nibble6: bit[27:24]
  • nibble7: bit[31:28]

So the result is.

32bit: 12345678
8 bits: 78 56 34 12
4 bit: 8 7 6 5 4 3 2 1

On a big-endian system, the result is different. The bit allocation is as follow.

  • nibble0: bit[31:28]
  • nibble1: bit[27:24]
  • ......
  • nibble6: bit[7:4]
  • nibble7: bit[3:0]
32bit: 12345678
8 bits: 12 34 56 78
4 bit: 1 2 3 4 5 6 7 8
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox