What is endianness and how do you check it in code?
Short answer: Endianness is the order in which the bytes of a multi-byte value are stored in memory. Little-endian stores the least significant byte at the lowest address (x86, almost all Arm systems in practice, RISC-V). Big-endian stores the most significant byte first (network byte order, older PowerPC, some DSPs and Motorola parts). You can check it at run time by looking at the first byte of a known integer.
value 0x12345678 at address 0x100
0x100 0x101 0x102 0x103
little-endian: 78 56 34 12
big-endian: 12 34 56 78
#include <stdint.h>
int is_little_endian(void)
{
uint32_t x = 1;
return *(const uint8_t *)&x == 1; /* lowest-addressed byte holds the LSB */
}
/* same idea with a union */
int is_little_endian_union(void)
{
union { uint32_t u; uint8_t b[4]; } v = { .u = 1 };
return v.b[0] == 1;
}
Reading an object through char */unsigned char */uint8_t * is always allowed (it does not violate strict aliasing), so the pointer version is valid C.
Compile-time check (GCC/Clang):
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
/* little-endian target */
#endif
Where endianness matters
- Communication: network protocols (TCP/IP headers are big-endian), CAN signals (Intel vs Motorola byte order in DBC files), Modbus (big-endian registers), USB and Bluetooth (little-endian).
- Files and flash data shared between different processors.
- Casting byte buffers to structs or integers.
The portable way: never depend on the host's endianness. Build and split values from bytes explicitly with shifts, which work on any host:
uint32_t get_be32(const uint8_t *b)
{
return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | (uint32_t)b[2] << 8 | b[3];
}
void put_le16(uint8_t *b, uint16_t v) { b[0] = (uint8_t)v; b[1] = (uint8_t)(v >> 8); }
Note the casts to uint32_t before shifting: without them, b[0] is promoted to int, and 0x80 << 24 overflows a signed int.
Arm detail: Arm cores are bi-endian in architecture, but Cortex-M endianness is fixed at chip design (almost always little-endian), and Linux on Arm is almost always little-endian.