What this course is, and how to use it
This is the third course in University Computer Science: computer systems fundamentals 计算机系统基础. It goes from a single bit to a running program: how numbers are stored as bits, how gates make decisions, how a processor steps through instructions, and how the operating system and the toolchain get your program onto the hardware.
A limit, stated once: this is a study course, not a degree. Every program fragment is original and complete in itself.
- Units 3.1–3.2 are the alphabet of the machine: bits, encoding and gates.
- Units 3.3–3.4 are the machine itself: processor, memory and instructions.
- Units 3.5–3.6 are the software around it: operating-system services and the compilation pipeline.
The habit to build: every layer makes a promise to the layer above it. Each unit names that promise, and you can check every conversion with a short script.
Binary and data encoding
Why it matters. Everything below the source code is bits. Knowing how numbers, fractions and text are encoded explains many surprises, from counters that overflow to 0.1 + 0.2 ≠ 0.3.


The idea.
| encoding | what it stores | rule |
|---|---|---|
| unsigned 无符号 | whole numbers $\ge 0$ | $n$ bits give $0$ to $2^n - 1$ |
| two's complement 二进制补码 | signed whole numbers | negate: flip all bits, add 1; range $-2^{n-1}$ to $2^{n-1} - 1$ |
| IEEE-754 IEEE-754 浮点 | real numbers, rounded | sign, biased exponent, fraction |
| ASCII ASCII 码 | basic text | 7 bits, 128 codes |
| Unicode 统一码 | all text | code points; UTF-8 uses 1 to 4 bytes |
In two's complement addition, the carry out of the top bit is always thrown away. Overflow 溢出 happens only when two numbers of the same sign give a result of the other sign.

Why two's complement is used everywhere. It turns subtraction into addition, $a - b = a + (-b)$, so one adder circuit does both. The reason is modular arithmetic: with $n$ bits, $-b$ and $2^n - b$ are the same number modulo $2^n$, and "flip all bits, add 1" computes exactly $2^n - b$. One circuit for + and − is cheaper, and that is why every modern processor uses it.
Worked example 1: conversion and overflow. Write $-73$ in 8-bit two's complement.
- $73 = 01001001_2$.
- Flip all bits: $10110110$.
- Add 1: $10110111$, which is $-73$.
Now add $96 + 64 = 160$. As unsigned, $10100000_2 = 160$ is fine. As signed 8-bit, the largest value is $127$, so this is overflow: the stored pattern reads $160 - 256 = -96$.
Worked example 2: a float surprise. In binary, $0.1$ never ends ($0.000110011\ldots$), so IEEE-754 rounds it. As a result, $0.1 + 0.2$ gives $0.30000000000000004$. This is a rounding 舍入 error, not a bug in the language. Also, the exponent sets the gap between neighbouring floats, so floats are not evenly spaced: they are close together near zero and far apart for large values.
Common mistakes.
- Thinking a bit pattern has one value. $10110111$ is $183$ unsigned but $-73$ signed: the bits stay the same, and the type decides how to read them.
- Testing floats for exact equality after arithmetic.
- Mixing up a character code and a number. The character "1" is stored as the code $49$, not as $1$.
Summary. Unsigned: $0$ to $2^n-1$. Two's complement: flip and add 1; one adder for + and −; throw away the top carry. IEEE-754: sign, exponent and fraction, with rounding. ASCII is 7-bit; Unicode uses code points; UTF-8 has variable width. $0.1 + 0.2 \ne 0.3$ because of rounding.
Logic gates and digital building blocks
Why it matters. Gates are where physics becomes logic. In the end, every program runs as ANDs, ORs and NOTs, and Boolean algebra is the tool that makes the circuits smaller.


The idea. The basic gates are AND, OR and NOT. A NAND 与非门 gate is universal: every other gate can be built from NAND gates alone. The main building blocks are:
- the half adder 半加器: XOR gives the sum bit, AND gives the carry;
- the full adder 全加器: two half adders and an OR gate. Full adders chained carry-to-carry make a ripple-carry adder;
- the multiplexer 多路选择器: a select line chooses which input reaches the output.

Why Boolean algebra makes circuits smaller. Identities such as $x + x = x$, $x \cdot x = x$ and $x + \bar{x} = 1$ show when two expressions have the same truth table, so one smaller circuit can replace a larger one. For example, the multiplexer expression $x = \bar{s}\,a + s\,b$ is already minimal, while a direct OR of every row where the output is 1 uses more gates. Fewer gates mean less power and less delay.
Worked example 1: adding one bit. Sum $s = a \oplus b$, carry $c = ab$.
- $1 + 0$: $s = 1$, $c = 0$.
- $1 + 1$: $s = 0$, $c = 1$ (binary 10).
Two gates give correct arithmetic. Chain four full adders to add 0101 + 0011.
Worked example 2: a 2-to-1 multiplexer in gates. Output $= \bar{s}a + sb$. When $s = 0$, $a$ passes; when $s = 1$, $b$ passes. A 4-to-1 multiplexer is three 2-to-1 multiplexers in two stages. A 32-to-1 multiplexer is the same idea, five stages deep.
Common mistakes.
- Writing XOR as OR. They differ on the $1 + 1$ row.
- Forgetting the delay of the carry chain: in a ripple-carry adder, each extra bit adds more gate delays.
- Thinking gates switch instantly. Gate delay is what limits the clock speed.
Summary. NAND is universal. Half adder: XOR + AND. Full adders chain, and the ripple-carry delay grows with the number of bits. Multiplexer: $\bar{s}a + sb$. Boolean identities make circuits smaller.
Processor and memory overview
Why it matters. The CPU runs a loop, and memory is built as a pyramid. These two pictures explain speed and cost, and why the cache 高速缓存 often matters more for performance than the clock speed.

The idea. The fetch-decode-execute cycle 取指-译码-执行周期 has three steps, repeated:
- Fetch: the PC (program counter) gives an address, and the instruction at that address is copied from memory into the IR (instruction register).
- Decode: the instruction is turned into control signals.
- Execute: the ALU calculates, memory is read or written, or the PC is changed. Normally the PC advances to the next instruction; for a four-byte instruction this is PC + 4.
The memory hierarchy, from fastest to slowest:
| level | typical speed | size |
|---|---|---|
| registers | under 1 ns | bytes |
| L1, L2, L3 cache | a few ns | KB to MB |
| DRAM (main memory) | about 100 ns | GB |
| SSD, then hard disk | much slower | TB |
Each level is bigger, cheaper per byte and slower than the one above.

Why the hierarchy exists. Fast memory costs more per byte, and big memory is slow: this is a physical trade-off. The hierarchy works because of locality 局部性:
- temporal locality: programs use the same small set of data again and again;
- spatial locality: programs use addresses that are close together.
So a small, fast cache can answer most memory requests.
Worked example 1: tracing three instructions.
LOAD R1, 0(R2): R1 changes (it gets the value at address R2).ADD R3, R1, R1: R3 changes (it gets 2 × R1).STORE R3, 0(R2): memory at address R2 changes.
The PC moves on by 4 after each instruction. A branch would write a new address into the PC instead.
Worked example 2: why data layout matters. Summing an array is limited by memory, not by arithmetic. Reading one cache line brings in 64 bytes that are next to each other, so going along rows (row-major order) is fast. The same loop going down columns is many times slower, with the same number of operations. Here the hierarchy decides the speed, not the clock.
Common mistakes.
- Mixing up the IR (instruction register) and the PC (program counter).
- Treating memory access time as constant. A cache hit and a cache miss can differ by a factor of 100 or more.
- Thinking the CPU sees physical memory directly. Virtual memory (unit 3.5) sits in between.
Summary. Fetch → decode → execute, then PC + 4. Register file, IR and ALU sit around the loop. Hierarchy: registers, cache, DRAM, SSD. Locality makes it work. Data layout can matter more than the amount of arithmetic.
Machine instructions
Why it matters. Assembly language is what every compiler produces, and every performance question ends there: registers, immediate values and memory moves.
The idea. Typical RISC instructions:
| instruction | what it does |
|---|---|
add rd, rs1, rs2 |
adds two registers |
addi |
adds an immediate (a constant in the instruction) |
lw / sw |
load a word from memory / store a word to memory, with addresses like 0(R2) |
beq / bne |
compare two registers and jump if equal / not equal |
Addressing modes 寻址方式: register, immediate, and base + offset. In RISC, memory is reached only through load and store.

Why RISC uses load and store only. When all instructions have one
simple shape, they decode quickly and work well in a pipeline. Every
memory access is a separate lw or sw, and arithmetic works only
between registers. CISC designs put memory access inside arithmetic
instructions. This makes programs shorter but harder to pipeline. The
trade-off is the number of instructions against the speed of each one.
Worked example 1: a loop in machine steps.
loop: addi R1, R1, -1
bne R1, R0, loop
Subtract 1, compare with zero (R0 always holds 0), and jump back: two
instructions for each pass. A countdown loop with a suitable initial counter can use this pair, together with its loop body; other while conditions need different tests.
Worked example 2: from C to instructions. a[i] = a[i] + 1
becomes lw (load), addi (add 1) and sw (store), with the index
scaled into the offset. Array indexing is address arithmetic, and a
pointer is a base register.
Common mistakes.
- Reading
0(R2)as the value 0. It means offset 0 from the address in R2. - Forgetting to set the loop-counter register before the loop.
- Using the index $i$ as the byte offset without scaling it by the element size ($4i$ for 4-byte words).
Summary. add, addi, lw, sw, beq. Memory only through load and store, with base + offset. A while loop becomes decrement-and-branch. Array indexing is scaled address arithmetic: a[i] + 1 is lw, addi, sw.
The operating-system interface
Why it matters. No program touches the hardware directly. The operating system shares the machine safely, and processes, virtual memory and files are the services every program uses.

The idea.
- A process 进程 is a program plus its running state: address space, registers and open files.
- A context switch 上下文切换 saves the state of one process and loads the state of another.
- Virtual memory 虚拟内存: each process sees its own addresses. The OS and the hardware (page tables and the TLB) map virtual addresses to physical ones.
- Files 文件 are named streams of bytes.
- System calls 系统调用 (
open,read,write,fork,execve) are the boundary where your code asks the kernel to do something.

Why virtual memory exists. One idea meets three needs:
- isolation: one process cannot read another's pages;
- more memory than is physically there, by moving pages to disk;
- convenience: programs can be linked to fixed addresses.
A page fault 缺页 happens when an access cannot go ahead with the current page mapping or permissions. The OS may then load or allocate a valid page. An access that is not allowed may instead end the process.
Worked example 1: what a context switch saves. Registers, the PC, the memory mappings and the open-file table: everything the next instruction of that process needs. CPU cache contents are not normally saved on a context switch; some cached data for the incoming process may still be present. The exact saved state depends on the system.
Worked example 2: a system call in C.
int fd = open(path, O_RDONLY);
read(fd, buf, 4096);
Each call traps into the kernel, runs with kernel privileges, and then
returns. Python's open and read use the same calls underneath: the
interface is the contract, and each language wraps it.
Common mistakes.
- Mixing up a process (its own memory) and a thread (shares memory with other threads of the same process).
- Thinking
mallocuses the disk. It allocates memory, not files. - Thinking a page fault is always a crash, or always a disk read. Many page faults are normal and handled, while accesses that are not allowed can fail.
Summary. Process = program + state; a context switch saves and loads that state. Virtual addresses map to physical ones through page tables. Page faults need the OS to handle them. System calls (open, read, write, fork, execve) are the boundary.
Compilation and execution path
Why it matters. Source code is not yet a program. The path from a
.c file to a running process has four stages. Each stage has its own
kind of error, and you can inspect the output of each one.
The idea.
- Preprocessor 预处理: expands
#includeand#define. It works on text only. - Compiler 编译器: turns C into assembly.
- Assembler 汇编器: turns assembly into object code. References to other files are still unresolved.
- Linker 链接器: resolves names across object files and libraries, and produces the executable.
The loader then starts the executable as a process (unit 3.5).

Why the stages are separate.
- Separate compilation: in a program of a million lines, only the changed file is compiled again.
- Libraries can be shared as object files or shared libraries.
- Each error belongs to one stage: macro errors, type errors, instruction errors, name (symbol) errors.
The pipeline saves real engineering time; it is not just a formality.
Worked example 1: the four files.
| stage | tool | output |
|---|---|---|
| preprocess | cpp | main.i |
| compile | cc1 | main.s |
| assemble | as | main.o |
| link | ld | prog |
The file extensions name the stages, and the right compiler flag lets you look at any of them.
Worked example 2: compiled and interpreted. C runs all four stages before the program starts: the result is fast, and specific to one machine. Python source is read and run by an interpreter: CPython first compiles it to bytecode, and a virtual machine runs the bytecode. The trade-off in one line: translate once and run many times, or translate every time you run.
Common mistakes.
- Calling every failure a compile error. "Undefined reference" comes from the linker.
- Forgetting that headers are just text: macros have no type.
- Thinking optimisation can never change float results. Reordering floating-point operations can.
Summary. cpp (text) → compiler (types) → assembler (instructions) → linker (names). "Undefined reference" is a linker error. Compiled and interpreted languages differ in when the translation happens.