Search topics...
CPU FundamentalsBus Architecture & Memory Typesfoundational

Little-endian vs big-endian — when does it matter in embedded?

0 upvotes
Practice with AISoon
Study the fundamentals first — CPU Fundamentals topic page

Endianness defines the byte order of multi-byte values in memory. Little-endian stores the least-significant byte at the lowest address — the 32-bit value 0x12345678 is stored as 78 56 34 12. Big-endian stores the most-significant byte first — the same value is stored as 12 34 56 78. ARM Cortex-M processors are little-endian by default (and most are little-endian only).

Endianness matters whenever firmware exchanges multi-byte data with an external system that uses a different byte order. The most common case is network protocols: TCP/IP, UDP, and virtually all Internet protocols define their headers in big-endian (called "network byte order"). When an embedded device constructs an IP packet, every 16-bit and 32-bit header field — source/destination port, sequence number, packet length — must be byte-swapped from the CPU's native little-endian to big-endian before transmission, and swapped back on reception. Similarly, many industrial protocols (Modbus TCP, CAN with J1939) define their payloads in big-endian.

ARM provides efficient hardware intrinsics for byte swapping: __REV(x) reverses the byte order of a 32-bit word (equivalent to htonl()), and __REV16(x) swaps bytes within each 16-bit halfword (equivalent to htons()). These compile to a single REV or REV16 instruction — one cycle on all Cortex-M cores. Using these intrinsics is far more efficient than the manual shift-and-OR approach that generic C implementations use. A common bug: forgetting to swap when parsing a network packet, leading to values that are off by orders of magnitude (e.g., a 16-bit port number 0x01BB (443) becomes 0xBB01 (47873)). Another trap: casting a uint8_t buffer pointer to a uint32_t* to read a multi-byte field — this both assumes alignment and ignores endianness, producing incorrect values and potential HardFaults on Cortex-M0 (which does not support unaligned access).

Source: CPU Fundamentals Q&A