Endianness defines the order in which bytes that represent large numerical values are stored in memory.
There are two types of endianness:
- Big-endian: The most significant byte is stored first. The 0x01020304 32-bit value is stored at the ptr address as follows:
Offset in memory Value ptr 0x01 ptr + 1 0x02 ptr + 2 0x03 ptr + 3 0x04
Examples of big-endian architectures are AVR32 and Motorola 68000.
- Little-endian: The least significant byte is stored first. The 0x01020304 32-bit value is stored at the ptr address as follows:
Offset in memory Value ptr 0x04 ptr + 1 0x03 ptr + 2 0x02 ptr + 3 0x01
The x86 architecture is little-endian.
- Bi-endian: Hardware supports switchable endianness. Some examples are PowerPC, ARMv3, and the preceding examples.
Endianness is particularly essential when exchanging data with other systems. If a developer sends the 0x01020304 32-bit integer as is, it may be read as 0x04030201 if the endianness of the receiver does not match the endianness of the sender. That is why data should be serialized.
This C++ snippet can be used to determine the endianness of a system:
#include <iostream>
int main() {
union {
uint32_t i;
uint8_t c[4];
} data;
data.i = 0x01020304;
if (data.c[0] == 0x01) {
std::cout << "Big-endian" << std::endl;
} else {
std::cout << "Little-endian" << std::endl;
}
}