liveBook · Manning

Encoding

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

An encoding is a representation that maps information such as instructions or data to a defined sequence of symbols or bits.

An encoding maps information to a defined sequence of symbols or bits. The same bit pattern can represent different values because the data type determines how it is interpreted, not the CPU alone. section 5.1

Text files are binary files that follow a consistent mapping between bit strings and characters. Arbitrary binary files remain opaque because they do not describe their meaning externally. section 5.1

One bit pattern, two numbers

Rust prints 1100001111000011 for both a u16 value of 50115 and an i16 value of -15421. The bits stay unchanged; the type supplies the interpretation.

Reinterpreting a float

A Rust program uses unsafe std::mem::transmute to view the bits of 42.42 as a u32, prints the 32-bit pattern, then converts it back and verifies equality. section 5.1

Instructions are encoded as numbers too, so operations and data share the same general representation. A software CPU can therefore emulate another computer’s instruction set; a CHIP-8 implementation programs directly in hexadecimal while exposing functions, pointers, and the stack. section 5.7

Listing 5.2 Interpreting a float’s bit string as an integer
 fn main() {
   let a: f32 = 42.42;
   let frankentype: u32 = unsafe {
     std::mem::transmute(a)             #1
   };
 
   println!("{}", frankentype);         #2
   println!("{:032b}", frankentype);    #3
 
   let b: f32 = unsafe {
     std::mem::transmute(frankentype)
   };
   println!("{}", b);
   assert_eq!(a, b);                    #4
 }

Inspect the complete Rust example that reinterprets a float’s bit string as an integer and converts it back. section 5.1

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

How deep it goes
Demonstrates bit reinterpretation in Rust and extends the idea to a hexadecimal CHIP-8 CPU implementation.
Examples
Uses signed and unsigned integers, float-to-integer reinterpretation, and a hexadecimal CHIP-8 implementation.
What it assumes
Assumes basic Rust familiarity while introducing bit patterns, unsafe reinterpretation, pointers, functions as data, and the stack.
What you can do after
Evaluate how types and instructions interpret bit patterns, and understand the foundations of a software CPU emulator.
How it connects
Connects encoding with type systems, binary files, text files, CPU instructions, pointers, functions, and the stack.

Also explained in

Compare how 9 books explain encoding →

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.