chapter five

5 Data in Depth

 

In this chapter:

  • Learn how data is represented in the computer
  • Build a working CPU emulator
  • Create your own a numeric data type
  • Understand the inner workings of floating point numbers

This chapter is all about understanding how zeroes and ones can be built up to become much larger objects such text, images and sound. We will also touch upon how computers do computation. By the end of the chapter, you will have emulated a fully-functional computer with CPU, memory and user-defined functions. You will break apart floating point numbers to create a numeric data type of your own making that only takes up a single byte. The chapter introduces a number of terms that may not be familiar to programmers who have never done systems programming, such as endianness and integer overflow.

5.1  Bit Patterns and Types

A small but important lesson is that a single bit pattern can mean different things. The type system of a higher-level language, such as Rust, is just an artificial abstraction over reality. Understanding this becomes important as you begin to unravel some of that abstraction and to gain a deeper understanding of how computers work.

Listing 5.2  is an example that uses the same bit pattern to represent two different numbers. The type system—not the CPU—is what makes the distinction.

Listing 5.1. Output of Listing 5.2 
a: 1100001111000011 50115
b: 1100001111000011 -15421

5.2  Life of an integer

5.2.1  Understanding Endianness

5.3  Decimal Numbers

5.3.1  About Floating Point

5.3.2  Looking inside an f32

5.3.3  About the Sign Bit

5.3.4  About the Exponent

5.3.5  About the Mantissa

5.3.6  Representing decimal numbers in a single byte with a fixed-point number format

5.4  Generating f32 values between 0 and 1 from random bytes

5.5  Implementing a CPU in Software to Establish that Functions are also Data

5.5.1  CPU 1: “the Adder”

5.5.2  First working emulator

5.5.3  CPU 2: “the Multi-Adder”

5.5.4  CPU 3: Adding functions