liveBook · Manning

Endianness

As explained in Rust in Action: Systems programming concepts and techniques

Endianness is the convention governing the order in which the bytes of a multibyte value are laid out in memory.

Endianness is the convention that determines how the bytes of a multibyte value are arranged in memory. Big-endian order places the most significant byte first; little-endian order places it last. The same bytes can therefore produce different integer values on different CPUs. section 5.2.1 section 5.8

A four-byte pattern makes the difference visible:

  • Big-endian order stores AA BB CC DD. section 5.2.1
  • Little-endian order stores DD CC BB AA. section 5.2.1
  • Byte significance follows powers of two, just as decimal significance follows powers of ten. section 5.2.1
  • Bit numbering is a related layout question inside an individual byte, but it is distinct from byte endianness. section 5.2.1

Inspecting endianness in Rust

A Rust program can reinterpret [0xAA, 0xBB, 0xCC, 0xDD] and its reversed sequence as i32 values with unsafe std::mem::transmute. The printed pair changes with the machine's byte order, making the portability problem concrete. section 5.2.1

Listing 5.6 Inspecting endianness
use std::mem::transmute;
 
fn main() {
  let big_endian: [u8; 4]    = [0xAA, 0xBB, 0xCC, 0xDD];
  let little_endian: [u8; 4] = [0xDD, 0xCC, 0xBB, 0xAA];
 
  let a: i32 = unsafe { transmute(big_endian)    };    #1
  let b: i32 = unsafe { transmute(little_endian) };    #1
 
  println!("{} vs {}", a, b);
}

Run the four-byte Rust inspection to compare the integer values produced by big-endian and little-endian layouts. section 5.2.1

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines byte order, derives significance from binary place values, and demonstrates the behavior with executable Rust code.
Examples
Uses AA BB CC DD byte sequences, reversed layouts, powers-of-two place values, and a Rust transmutation program.
What it assumes
Introduces byte significance and binary powers of two for readers unfamiliar with systems-programming terminology.
What you can do after
Evaluate how a byte pattern will be interpreted and inspect a machine's endianness with a Rust program.
How it connects
Connects byte order with CPUs, integer types, executable files, binary representation, and bit numbering.

Also explained in

Compare how 3 books explain endianness →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.