跳到主要内容

计算机系统基础

大学计算机科学知识点 3

本主题的视频课程 打开视频页面
5:52

计算机系统基础

本课程追踪程序从单个比特到运行中的进程的全过程。前两个单元介绍基础:比特如何编码数据,以及逻辑门如何用它们进行计算。接下来的两个单元介绍机器:处理器、存储器及其指令。最后两个单元介绍周边机制:操作系统和编译工具链。每一层都与下一层有一个约定。

英文讲解 · 可切换中英文字幕

探索

One pattern, two readings

The pattern 10110111 reads 183 unsigned and −73 in 8-bit two's complement. Change the value and see the top bit carry weight −128.

探索

The carry ripples through 0101 + 0011

$2C_{out}+S=A+B+C_{in}$

Step the four full adders from the right. Three columns each produce a carry before the top bit settles, giving 1000 = 8.

讲义

English

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.

A single-digit seven-segment LED display component, showing its seven separate bars
A seven-segment display shows one denary digit, often driven by BCD
A table of four 8-bit patterns read twice: 00000000 is 0 either way, 01111111 is 127 unsigned and +127 signed, 10000000 is 128 unsigned but -128 signed, and 11111111 is 255 unsigned but -1 signed
The same byte read as unsigned and as signed: only the agreed interpretation tells them apart

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.

Bit-layout boxes for integers and IEEE floats
The same 32 bits read three ways: unsigned, two's complement, and an IEEE float — layout is the meaning

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.

  1. $73 = 01001001_2$.
  2. Flip all bits: $10110110$.
  3. 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.

Three small black computer chips with rows of metal pins, each printed with a code
A real logic chip: the package holds several gates whose pins are wired as in a gate diagram
Gate schematic of the full adder: two XOR gates for the sum, two AND gates and an OR for the carry, with inputs A, B, Cin wired through
The full adder: five gates, one of the most-reused circuits in computing

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.
Gate schematic: half adder, full adder, multiplexer
XOR-and-AND make a half adder; two make a full adder; a mux picks a lane

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.

A motherboard seen from above: the CPU socket, memory slots and expansion slots joined by dense printed tracks
A motherboard: the CPU, memory and I/O all sit on one set of buses — the printed tracks running between them

The idea. The fetch-decode-execute cycle 取指-译码-执行周期 has three steps, repeated:

  1. Fetch: the PC (program counter) gives an address, and the instruction at that address is copied from memory into the IR (instruction register).
  2. Decode: the instruction is turned into control signals.
  3. 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.

CPU and memory block diagram
The fetch-decode-execute loop around the register file, with the memory pyramid alongside

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.

  1. LOAD R1, 0(R2): R1 changes (it gets the value at address R2).
  2. ADD R3, R1, R1: R3 changes (it gets 2 × R1).
  3. 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.

Instruction and register trace
Each line: fetch, execute, the register delta — a loop unrolled into its machine steps

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.

A context switch saves process A's state (its PCB) and loads process B's
A context switch saves one process's state and loads another's

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.
The OS layer between programs and hardware
System calls cross the boundary; the kernel shares CPU, memory and devices among processes

Why virtual memory exists. One idea meets three needs:

  1. isolation: one process cannot read another's pages;
  2. more memory than is physically there, by moving pages to disk;
  3. 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 malloc uses 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.

  1. Preprocessor 预处理: expands #include and #define. It works on text only.
  2. Compiler 编译器: turns C into assembly.
  3. Assembler 汇编器: turns assembly into object code. References to other files are still unresolved.
  4. Linker 链接器: resolves names across object files and libraries, and produces the executable.

The loader then starts the executable as a process (unit 3.5).

The toolchain pipeline
Preprocess, compile, assemble, link — each stage its own file format and its own error class

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.

词汇
English 中文 拼音
two's complement/tuːz ˈkɒmplɪmənt/ 二进制补码 èr jìn zhì bǔ mǎ
unsigned/ʌnˈsaɪnd/ 无符号 wú fú hào
IEEE-754/ˌaɪ iː iː ˈiː ˈsevənhʌndrɪdn ˈfɪfti fɔː/ IEEE-754 浮点 IEEE-754 fú diǎn
ASCII/ˈæski/ ASCII 码 ASCII mǎ
Unicode/ˈjuːnɪkəʊd/ 统一码 tǒng yī mǎ
NAND/nænd/ 与非门 yǔ fēi mén
half adder/hɑːf ˈædə/ 半加器 bàn jiā qì
full adder/fʊl ˈædə/ 全加器 quán jiā qì
multiplexer/ˈmʌltɪpleksə/ 多路选择器 duō lù xuǎn zé qì
fetch-decode-execute cycle/fetʃ dɪˈkəʊd ˈeksɪkjuːt ˈsaɪkl/ 取指-译码-执行周期 qǔ zhǐ - yì mǎ - zhí xíng zhōu qī
cache/kæʃ/ 高速缓存 gāo sù huǎn cún
locality/ləʊˈkælɪti/ 局部性 jú bù xìng
addressing mode/əˈdresɪŋ məʊd/ 寻址方式 xún zhǐ fāng shì
process/ˈprəʊses/ 进程 jìn chéng
context switch/ˈkɒntekst swɪtʃ/ 上下文切换 shàng xià wén qiè huàn
virtual memory/ˈvɜːtʃuːəl ˈmeməri/ 虚拟内存 xū nǐ nèi cún
page fault/peɪdʒ fɒlt/ 缺页 quē yè
system call/ˈsɪstəm kɔːl/ 系统调用 xì tǒng diào yòng
linker/ˈlɪŋkə/ 链接器 liàn jiē qì
assembler/əˈsemblə/ 汇编器 huì biān qì
preprocessor/prɪˈprəʊsesə/ 预处理 yù chǔ lǐ
computer systems fundamentals/kəmˈpjuːtə ˈsɪstəmz ˌfʌndəˈmentlz/ 计算机系统基础 jì suàn jī xì tǒng jī chǔ
overflow/ˌəʊvəˈfləʊ/ 溢出 yì chū
rounding/ˈraʊndɪŋ/ 舍入 shě rù
files/faɪlz/ 文件 wén jiàn
compiler/kəmˈpaɪlə/ 编译器 biān yì qì

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP