cpp core · medium

Endianness & Byte Order

Endianness decides the in-memory byte order of multi-byte integers. Little-endian (x86, ARM) stores the least-significant byte at the lowest address; big-endian stores the most-significant byte first and is also the canonical 'network byte order'. The numeric value is identical — only the raw bytes differ — so any time integers cross between machines you must normalize with htonl/ntohl (or std::byteswap / std::endian in C++20/23).

🔑 Key line

Endianness is which byte of a multi-byte value lives at the lowest address: little-endian (x86/ARM) puts the LSB first, big-endian (network order) puts the MSB first — convert with htonl/ntohl at any cross-machine boundary.

The code

uint32_t x = 0x0A0B0C0D; // MSB = 0A, LSB = 0D
auto* p = reinterpret_cast<unsigned char*>(&x);
// little-endian (x86, ARM): p[0]=0x0D p[1]=0x0C p[2]=0x0B p[3]=0x0A
// big-endian (network): p[0]=0x0A p[1]=0x0B p[2]=0x0C p[3]=0x0D
uint32_t net = htonl(x); // host -> network (big-endian)
uint32_t hst = ntohl(net); // network -> host

What this lesson walks through

  1. 01An int is just four bytes
  2. 02Little-endian: LSB first
  3. 03...and MSB at the top
  4. 04Big-endian: MSB first
  5. 05Same value, mirrored layout
  6. 06Network byte order = big-endian
  7. 07Normalize at the boundary

0x0A0B0C0D is a 32-bit value made of four bytes: 0A is the most-significant, 0D the least. The only question is which one the CPU stores at the lowest memory address.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Endianness & Byte Order and 100+ animated C++ interview lessons.

← Previous
Struct Alignment & Padding
Next →
Static Initialization Order Fiasco