Skip to content

Byte Order and Endianness

Let's start with a simple question: How do you store the number 12345 in memory?

The number 12345 in hexadecimal is 0x3039. Since this is a 16-bit number, it takes up 2 bytes. But here's the question: which byte goes first in memory?

cpp
Number: 12345 (0x3039)
Bytes:  0x30 and 0x39

You have two choices:

  1. Store 0x30 first, then 0x39 (big endian)
  2. Store 0x39 first, then 0x30 (little endian)

The Two Approaches: Big Endian vs Little Endian

Big Endian: Most Significant Byte First

In big endian systems, the most significant byte (the "biggest" part of the number) is stored first in memory.

cpp
Number: 12345 (0x3039)
Memory: [0x30][0x39]  (most significant byte first)

Think of it like reading a number from left to right - you read the biggest part first.

Little Endian: Least Significant Byte First

In little endian systems, the least significant byte (the "smallest" part of the number) is stored first in memory.

cpp
Number: 12345 (0x3039)
Memory: [0x39][0x30]  (least significant byte first)

Think of it like reading a number from right to left - you read the smallest part first.

Why Does This Matter?

Different Architectures Use Different Endianness

  • Intel x86 processors: Little endian
  • ARM processors: Can be either (configurable)
  • Network protocols: Traditionally big endian (network byte order)
  • Some older systems: Big endian

The Problem: Data Exchange

When computers with different endianness try to exchange data, they can misinterpret each other's numbers.

Example:

  • Computer A (little endian) sends: [0x39][0x30] (meaning 12345)
  • Computer B (big endian) receives: [0x39][0x30] (interprets as 15672)

The same bytes mean different numbers on different systems!

Real-World Examples

Example 1: Network Communication

When you send data over the network, you need to ensure both sides interpret the data the same way.

Example 2: File Formats

Many file formats specify their byte order to ensure compatibility.

PNG files: Always big endian JPEG files: Always big endian Some binary formats: May use either, specified in header

Example 3: Hardware Registers

Different hardware components might use different endianness, requiring conversion when reading registers.

Detecting Endianness

How can you tell if your system is little endian or big endian?

Implement a function to detect if the current system is little endian or big endian. Return true if the system is little endian, false if it's big endian.

cpp
// TODO: Implement functions to detect if the current system is little endian or big endian
// Return true if the system is little endian, false if it's big endian

bool isLittleEndian() {
    // TODO: Your code here

    return false; // Placeholder return
}