TactivergeOffline

Digital Logic and Computer Architecture

From one bit to a pipelined processor and the chip it runs on

Ten chapters that climb from a single yes-or-no signal to gates, adders, state machines, an instruction set, a pipeline, caches and the physics and economics of the chip itself. Each chapter composes Tactiverge School lessons, so every explanation comes with its interactive diagram and server-checked practice.

Version 1 · Technically checked (automated checks only) · 10 chapters · 74 practice questions (questions only)

Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.

1. Information as bits

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A computer never stores "seven" or "red". It stores patterns of two-valued signals, and a code that everyone agrees on gives each pattern a meaning. This chapter starts there: why machines choose fixed steps over smooth values, why every extra bit doubles what you can say, how place value works in base 2, and what happens when a number no longer fits.

Figure 1.1. Every bit doubles the patterns (described in words)

Three columns of boxes. One bit gives 2 patterns (0, 1). Two bits give 4 patterns (00 to 11). Three bits give 8 patterns (000 to 111). A label reads: n bits give 2^n patterns.

Explanation

1.1 Analog and digital: smooth worlds, stepped machines

A thermometer's red line can sit anywhere. A digital thermometer shows 21.5 or 21.6, never in between. What did it throw away?

Analog: any value

An analog quantity can take any value in a range: the temperature might be 21.4 °C, 21.43 °C or 21.4372 °C. A clock with sweeping hands, a dimmer switch and the height of water in a bath are analog.

Digital: fixed steps

A digital value can only be one of a fixed list of steps. A digital thermometer that shows one decimal place has steps of 0.1 °C: 21.4, 21.5, 21.6. Turning an analog signal into steps is called analog-to-digital conversion. Smaller steps are more precise but need more storage.

The simplest step: a threshold

The roughest possible conversion has just two steps: yes or no, 1 or 0. Pick a threshold: above it is 1, otherwise 0. A night light turns on below a brightness threshold; a sorting machine calls a part 'red' above a redness threshold. Readings close to the line are where mistakes happen, so engineers test them carefully.

Common mix-ups

1.2 Bits: how much can two lights say?

A lighthouse can only flash on or off. How many different messages could you send with three lamps?

A bit is one choice

A bit (short for binary digit) is the smallest piece of information: 0 or 1. Inside a machine it could be a switch off or on, a voltage low or high, a hole punched or not, a magnet pointing one way or the other.

Every bit doubles the patterns

1 bit: 2 patterns. 2 bits: 4 (00, 01, 10, 11). 3 bits: 8. 4 bits: 16. n bits give 2 × 2 × … × 2 (n times) = 2ⁿ patterns. That's why 8 bits (one byte) already give 256 patterns, enough for every letter, digit and symbol on a keyboard.

A code gives patterns meaning

Patterns mean nothing until people agree a code. A 2-bit code for a robot might be: 00 = stop, 01 = left, 10 = right, 11 = forward. The same pattern can mean different things in different codes, so the sender and receiver must use the same one.

Common mix-ups

1.3 Counting with only 0 and 1

You count 8, 9, 10 because you have ten fingers. How would you count if you only had two?

Place value, the familiar way

In ordinary decimal numbers each place is worth ten times the one to its right: ones, tens, hundreds. 352 means 3 × 100 + 5 × 10 + 2 × 1. You carry when a place goes past 9.

Place value in base 2

In binary, each place is worth two times the one to its right: 1, 2, 4, 8, 16, 32, 64, 128. Each place holds only 0 or 1. To read 1011, put the place values over the bits: 8, 4, 2, 1. Add the places with a 1: 8 + 2 + 1 = 11.

Counting up

0, 1, 10, 11, 100, 101, 110, 111, 1000… The rightmost bit flips every time. The next flips every 2 counts, the next every 4, the next every 8. It's the same carrying you already know, just carrying at 2 instead of 10.

Common mix-ups

1.4 Converting: binary to decimal and back

A robot's register shows 1001 1100. Is the motor speed high or low? First you need to translate.

Binary → decimal: add the places

Write the place values above the bits, then add the place values that sit over a 1. For 1001 1100: places 128, 64, 32, 16, 8, 4, 2, 1. The 1s are under 128, 16, 8 and 4. Total: 128 + 16 + 8 + 4 = 156.

Decimal → binary: biggest place that fits
  1. Find the biggest place value that fits into your number. Put a 1 there.
  2. Subtract it.
  3. Repeat with what's left. Any place you skip gets a 0.

22: 16 fits (22 − 16 = 6). 8 doesn't (0). 4 fits (6 − 4 = 2). 2 fits (2 − 2 = 0). 1: 0. So 22 = 10110.

Always check by going back

Convert your answer back: 10110 → 16 + 4 + 2 = 22. ✔ It takes seconds and catches most mistakes. Engineers call this a round-trip check.

Common mix-ups

1.5 Running out of bits: overflow

In 2014 a video got so many views that YouTube's view counter nearly ran out of room. How can a computer run out of numbers?

The biggest number

With every bit on, n bits hold 2ⁿ − 1. 4 bits: 1111 = 15. 8 bits: 11111111 = 255. The '− 1' is because one of the 2ⁿ patterns is used for 0.

Overflow: wrapping round

Add 1 to the biggest number and every bit carries, but the final carry has nowhere to go. The counter shows all zeros. It's like a car's old mileage counter rolling from 99999 to 00000. The machine doesn't complain: it just shows a wrong answer, which is what makes overflow dangerous.

Choosing enough bits

Engineers ask: what's the biggest value this number could ever reach? Then they pick enough bits, plus a safety margin. A step counter for a day might reach 50,000 steps: 16 bits (up to 65,535) is enough. A counter of all views on a video needs far more. In 2014 YouTube's view counter, a 32-bit number that tops out at 2,147,483,647, was upgraded to 64 bits as one video got close to that limit.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Analog and digital: smooth worlds, stepped machines: example 1

A light sensor reads 0 (dark) to 1,000 (bright). The night light rule is: ON if the reading is below 200. Readings are 150, 200 and 640. What does the light do each time?

Bits: how much can two lights say?: example 1

A robot needs commands for: stop, forward, back, left, right and beep. What is the fewest bits per command?

Counting with only 0 and 1: example 1

Read the binary number 10110.

Converting: binary to decimal and back: example 1

Convert 37 to binary.

Converting: binary to decimal and back: example 2

Convert 0110 1001 to decimal.

Running out of bits: overflow: example 1

A parking-garage counter must count up to 600 cars. How many bits does it need?

Interactive figures, in words

Figure 1.2 from “Bits: how much can two lights say?”

Use the 4-bit register. Starting from all off, press 'Add 1' over and over and write down every pattern until it wraps back to 0000. How many patterns did you find? Now imagine adding a fifth switch.

The binary switches diagram shows a row of 4 (or 8) switches, each showing 0 or 1. Pressing 'Add 1' repeatedly steps through every pattern: 0000, 0001, 0010, up to 1111, which is 16 patterns for 4 bits, and then wraps back to 0000.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. A sensor measures distances from 0 to 2 m in 200 equal steps. How big is each step, in centimetres?

Answer: cm

Check it in “Analog and digital: smooth worlds, stepped machines”

2. A vending machine has 10 buttons. What is the smallest number of bits that can give each button its own pattern?

Answer: bits

Check it in “Bits: how much can two lights say?”

3. The pattern 10 means 'turn right' to one robot and 'beep' to another. Why?

  • One robot is broken
  • Patterns only mean something through an agreed code
  • Bits change meaning randomly
  • 10 is always 'ten'

Check it in “Bits: how much can two lights say?”

4. In binary, what is the place value of the 5th bit from the right?

Answer:

Check it in “Counting with only 0 and 1”

5. Convert the 8-bit binary number 10011100 to decimal.

Answer:

Check it in “Converting: binary to decimal and back”

6. Write 7 in binary. Type just the 0s and 1s with no leading zeros (for example, six is 110).

Answer:

Check it in “Converting: binary to decimal and back”

7. An 8-bit counter holds 255 and you add 3. What does it show? (It wraps round after 255.)

Answer:

Check it in “Running out of bits: overflow”

8. What is the smallest number of bits a counter needs to reach 1,000?

Answer: bits

Check it in “Running out of bits: overflow”

Engineering applications

Sensor readings

A microcontroller's analogue-to-digital converter turns a voltage into an integer. A 10-bit converter has 2^10 = 1024 steps, so the bit count sets the smallest change it can notice.

Counters that wrap

An 8-bit counter holds 0 to 255. Add one to 255 and it reads 0 again. Engineers pick widths so a timer or tally cannot wrap during the longest run the machine will ever do.

Summary

Glossary

Bits and bytes
A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
Binary place value
In binary each digit position is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. A number's value is the sum of the place values that hold a 1.
Word size
A processor's word size is the number of bits it naturally handles in one operation: its register width and usually its main data path.
ADC resolution
An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect.

Project: Design a status code

A delivery robot must report one of 11 states (idle, loading, moving and so on) over a few signal wires. Choose the smallest number of bits that can do it, assign a pattern to every state, and decide what the unused patterns should mean.

Deliverables

  • A table of every state with its bit pattern
  • A one-line argument for why fewer bits would not work
  • A rule for what the receiver does with an unused pattern

References

2. Logic gates and Boolean algebra

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A logic gate is a rule that turns input bits into an output bit. AND, OR and NOT are enough to describe any yes-or-no decision a machine makes, from a microwave door interlock to a sorting rule. Truth tables check every case; Boolean algebra and Karnaugh maps make the circuit smaller without changing what it does.

Figure 2.1. An AND gate and its truth table (described in words)

An AND gate symbol with inputs A and B and output Y, beside a four-row truth table: A=0 B=0 gives Y=0, A=0 B=1 gives 0, A=1 B=0 gives 0, A=1 B=1 gives 1.

Explanation

2.1 AND, OR, NOT: the three little deciders

A factory press only slams down if the worker has BOTH hands on the buttons. How does a machine check 'both'?

Inputs and outputs are bits

A logic gate takes one or two inputs, each 0 (off, false, no) or 1 (on, true, yes), and produces one output by following a fixed rule. In real circuits, 0 and 1 are low and high voltages; inside a lab simulation they are just numbers.

The three basic gates
Plus three useful extras

Amazingly, NAND on its own can be wired up to make every other gate.

Common mix-ups

2.2 Logic gates and truth tables

Every decision your phone makes, from unlocking to sending a message, comes down to a few kinds of tiny switch. How few kinds?

Bits as voltages

Digital circuits treat a voltage near the supply (say 3.3 V or 5 V) as 1 and near 0 V as 0. Anything in between is avoided. Because only two levels matter, small amounts of noise do not change the answer.

The basic gates

NOT flips its input. AND gives 1 only if all inputs are 1. OR gives 1 if any input is 1. XOR gives 1 if the inputs differ. NAND and NOR are AND and OR followed by NOT. Engineers write them as ¬A, A·B, A + B and A ⊕ B.

A truth table says everything

List every input combination in counting order (00, 01, 10, 11) and write the output. That table completely defines the gate: two circuits with the same truth table do the same job, however different they look.

Gates are made of transistors

A transistor is a switch made from doped silicon (week 10): a voltage on one terminal lets current flow between the other two. Two transistors in series make a NAND-like path; in parallel, a NOR-like one. That is how a material property becomes logic.

Common mix-ups

2.3 From safety rules to Boolean expressions

'The press may run only when the guard is shut, a hand is on each button and there is no fault.' Can you write that as one line of algebra?

Name the signals first

Give every input a letter and say what 1 means: G = 1 'guard closed', P = 1 'operator present', F = 1 'fault reported'. Writing what 1 means avoids the most common bug: a signal that is 1 when you thought it was 0.

Words to operators

'and', 'both', 'all' → ·. 'or', 'either', 'any' → +. 'not', 'no', 'unless' → ¬ (often 'X unless Y' becomes X · ¬Y). 'one or the other but not both' → ⊕. So the interlock is Y = G · P · ¬F.

Brackets carry meaning

AND binds tighter than OR, just as × binds tighter than +. A · B + C means (A · B) + C. If the rule says 'A and either B or C', write A · (B + C). When unsure, add brackets and check the truth table.

Check all three views

The expression is compact, the truth table is complete, and the gate diagram is what you build. If they disagree, one of them is wrong. For safety rules, read every row of the truth table aloud: 'guard open, operator present, no fault: machine off.'

Common mix-ups

2.4 Module check: simplifying logic

A 'majority vote' circuit can be written with 12 letters, or with 6. Both give identical answers. Why would an engineer care which one you build?

Useful laws

Identity: A·1 = A, A + 0 = A. Null: A·0 = 0, A + 1 = 1. Complement: A·¬A = 0, A + ¬A = 1. Idempotent: A + A = A. Absorption: A + A·B = A. De Morgan: ¬(A·B) = ¬A + ¬B; ¬(A + B) = ¬A · ¬B. Each can be proved with a four-row truth table.

The Karnaugh map

A K-map is a truth table folded into a grid whose columns go 00, 01, 11, 10 (Gray code), so neighbouring cells differ in exactly one input. A group of two neighbouring 1s drops that input; a group of four drops two inputs. Cover every 1 with as few, as large groups as possible.

Always verify

A simplification is correct only if its truth table matches the original on every row. The explorer and the K-map both do this check for you; on paper, compare the two output columns.

Derivation: Two simplifications, step by step
  1. Distributive law (factor out A): A·B + A·¬B = A·(B + ¬B).

  2. Complement law: B + ¬B = 1, because exactly one of them is 1. So the expression is A·1 = A.

  3. De Morgan's law: ¬(A · B) = ¬A + ¬B and ¬(A + B) = ¬A · ¬B. Check by truth table: ¬(A·B) is 1,1,1,0 for AB = 00, 01, 10, 11, and so is ¬A + ¬B.

  4. Majority: the row-by-row form is ¬A·B·C + A·¬B·C + A·B·¬C + A·B·C. Copy A·B·C three times (X + X = X), pair it with each other term and use the complement law: (¬A + A)·B·C + A·(¬B + B)·C + A·B·(¬C + C) = B·C + A·C + A·B, 6 literals instead of 12.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

AND, OR, NOT: the three little deciders: example 1

A safe opens only if the right code is entered AND the key is turned. The code is right (1) but the key isn't turned (0). Does it open?

Logic gates and truth tables: example 1

Write the truth table of A NAND B.

From safety rules to Boolean expressions: example 1

'The fan runs if the temperature is high, unless the maintenance switch is on.' Write it as an expression.

Module check: simplifying logic: example 1

Simplify A + A · B and check with a truth table.

Interactive figures, in words

Figure 2.2 from “AND, OR, NOT: the three little deciders”

Pick AND. Before flipping anything, predict the output for all four input combinations. Then check them. Do the same for OR and NOT. Which gate gives 1 most often?

The logic gate diagram lets you choose AND, OR, NOT, NAND, NOR or XOR, flip inputs A and B between 0 and 1, and see the output lamp. A truth table lists every input combination with its output and highlights the current row. AND gives 1 only for 1,1; OR gives 0 only for 0,0; NOT flips its one input.

Figure 2.3 from “From safety rules to Boolean expressions”

Start from the interlock preset A · B · ¬C (A = guard closed, B = operator present, C = fault). Toggle the inputs to find the only row where Y = 1. Then type A · (B + C) and compare it with A · B + C: find a row where they differ. Finally write your own rule for a door alarm and check its truth table.

The explorer takes a typed Boolean expression and shows three views: input switches with a live output, a gate diagram drawn from inputs on the left to the output on the right, and a full truth table with the current row marked. For the interlock A · B · ¬C, Y = 1 only on row 110: guard closed, operator present, no fault.

Figure 2.4 from “Module check: simplifying logic”

Load the majority preset and compare the row-by-row form with the simplest form. Toggle cells to make Y = A: how many literals does it need? Load 'XOR of three' and explain why nothing groups. Finally make up a function with four 1s that simplifies to a single two-letter term.

The K-map shows eight cells in two rows (A = 0, 1) and four columns (BC = 00, 01, 11, 10). Pressing a cell toggles its output. The tool lists the groups and the simplest expression: majority (rows 3, 5, 6, 7) simplifies to A·B + A·C + B·C; rows 4 to 7 simplify to A; three-input XOR (rows 1, 2, 4, 7) does not simplify.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. A microwave heats only if the door is shut and you pressed start. Which gate?

  • OR
  • AND
  • NOT
  • XOR

Check it in “AND, OR, NOT: the three little deciders”

2. When does A XOR B output 1?

  • When both inputs are 1
  • When the inputs are different
  • When at least one input is 1

Check it in “Logic gates and truth tables”

3. How many rows does the truth table of a 4-input gate have?

Answer: rows

Check it in “Logic gates and truth tables”

4. Machine runs only if the guard is closed (G), the operator is present (P) and there is no fault (F = 1 means fault). Which expression?

  • G + P + ¬F
  • G · P · F
  • G · P · ¬F

Check it in “From safety rules to Boolean expressions”

5. 'The light is on if it is dark (D), unless the switch is off (S = 1 means switch off).' Which expression?

  • D + S
  • D · ¬S
  • ¬D · S

Check it in “From safety rules to Boolean expressions”

6. By De Morgan's law, ¬(A + B) equals…

  • ¬A + ¬B
  • ¬A · ¬B
  • A · B

Check it in “Module check: simplifying logic”

7. On a three-input K-map, four 1s form one group (a whole row or a 2 × 2 block). The resulting term has…

  • Three literals
  • Two literals
  • One literal

Check it in “Module check: simplifying logic”

Engineering applications

Safety interlocks

A press may run only when both guards are closed AND the operator's two hands are on the buttons. Writing the rule as a Boolean expression lets you check all input cases before anyone stands near the machine.

Smaller circuits

Simplifying an expression with Boolean laws or a Karnaugh map removes gates without changing the truth table. Fewer gates means less area, less power and fewer places for a fault.

Summary

Glossary

Truth table
A truth table lists the output of a logic function for every possible combination of its inputs; n inputs need 2^n rows.
AND gate
An AND gate outputs 1 only when all of its inputs are 1.
OR gate
An OR gate outputs 1 when at least one of its inputs is 1.
NOT gate (inverter)
A NOT gate has one input and outputs its opposite: 0 becomes 1 and 1 becomes 0.
XOR gate
An XOR gate outputs 1 when its inputs are different and 0 when they are the same.
De Morgan's laws
NOT (A AND B) equals (NOT A) OR (NOT B), and NOT (A OR B) equals (NOT A) AND (NOT B).

Project: Specify a three-sensor interlock

A conveyor must stop if a light curtain is broken, OR if the cover is open while the belt is running. Name the signals, write the expression, build the full truth table, simplify it and show the simplified version gives the same table.

Deliverables

  • Signal names with what 1 means for each
  • The full truth table
  • The simplified expression with each law used
  • A row-by-row check that both versions agree

References

3. Combinational building blocks

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Engineers rarely design with single gates. They reuse a small set of blocks: the adder that does arithmetic, the multiplexer that chooses between signals and the decoder that points at one of many outputs. This chapter builds each block from gates, and shows that the NAND gate on its own can make all of them.

Figure 3.1. A half adder from two gates (described in words)

Inputs A and B each feed an XOR gate and an AND gate. The XOR output is the sum bit S and the AND output is the carry bit C. A table shows 0+0 gives C=0 S=0, 0+1 and 1+0 give C=0 S=1, and 1+1 gives C=1 S=0.

Explanation

3.1 Everything from NAND

If you could only manufacture one kind of gate, could you still build a whole computer? Engineers found the answer is yes, twice.

NOT and AND

NOT A = NAND(A, A). A AND B = NOT(NAND(A, B)), which is two NANDs: one NAND, then a NAND with its inputs tied as a NOT.

OR via De Morgan

De Morgan says A + B = ¬(¬A · ¬B), which is NAND(¬A, ¬B). So OR takes three NANDs: two as NOTs on the inputs, and one to combine them.

XOR in four

Let g1 = NAND(A, B). Then g2 = NAND(A, g1), g3 = NAND(B, g1), and Y = NAND(g2, g3) = A ⊕ B. Check row 11: g1 = 0, g2 = 1, g3 = 1, Y = 0. Row 10: g1 = 1, g2 = 0, g3 = 1, Y = 1.

Why one gate type helps

A factory that makes one well-tested cell can tile it millions of times. Designers still use many gate types today, but the fact that NAND (or NOR) is universal shows how little you need to compute anything.

Common mix-ups

3.2 Half adders and full adders

In binary, 1 + 1 = 10. A computer does that with two gates. How many does it need to add 1 + 1 + 1?

Column addition in binary

Binary adds like decimal, with only two digits: 0 + 0 = 0, 0 + 1 = 1, 1 + 1 = 10 (write 0, carry 1), 1 + 1 + 1 = 11 (write 1, carry 1).

The full adder table

For A B Cin = 000, 001, 010, 011, 100, 101, 110, 111, the outputs Cout S are 00, 01, 01, 10, 01, 10, 10, 11. In other words, Cout S is just the count of 1s written in binary.

Chaining adders

To add 4-bit numbers, line up four full adders, one per column. Each carry out feeds the next column's carry in, so the carry ripples from right to left. Next week you will add multi-bit numbers this way and see what happens when the answer is too big.

Derivation: Building the full adder
  1. Half adder (two inputs): the sum is 1 when exactly one input is 1, so S = A ⊕ B; the carry is 1 only when both are 1, so C = A · B.

  2. Full adder (three inputs A, B, Cin): the column total A + B + Cin is 0, 1, 2 or 3, written as two bits Cout S.

  3. S is 1 when the total is odd (1 or 3), which is when an odd number of inputs are 1: S = A ⊕ B ⊕ Cin.

  4. Cout is 1 when the total is 2 or 3. Either A and B are both 1 (A·B), or exactly one of them is 1 and there is a carry in (Cin·(A ⊕ B)). So Cout = A·B + Cin·(A ⊕ B).

  5. This is two half adders and an OR: the first adds A and B, the second adds Cin to that sum, and either carry makes Cout.

Common mix-ups

3.3 Multiplexers and decoders: choosing and pointing

A robot has eight sensors but only one analog-to-digital converter. How does it read them all through one input?

Multiplexer: a selector

A 2:1 multiplexer has data inputs A and B and a select input S. If S = 0 the output copies A; if S = 1 it copies B: Y = ¬S·A + S·B. A 4:1 mux uses two select bits; an 8:1 mux uses three.

Decoder: a pointer

A decoder takes an n-bit number and switches on exactly one of 2ⁿ outputs. A 2-to-4 decoder with inputs A1 A0 has outputs D0 = ¬A1·¬A0, D1 = ¬A1·A0, D2 = A1·¬A0, D3 = A1·A0. Give it 10 and only D2 lights.

Where machines use them

A microcontroller uses a mux to connect one of its many analog pins to its single converter. Memory uses decoders to switch on one row out of thousands. A processor uses muxes to choose which register feeds the adder.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Everything from NAND: example 1

Show that NAND(NAND(A, A), NAND(B, B)) is A OR B.

Half adders and full adders: example 1

Use the full adder equations for A = 1, B = 0, Cin = 1.

Multiplexers and decoders: choosing and pointing: example 1

A 2:1 mux has A = 0, B = 1, S = 1. What is Y?

Interactive figures, in words

Figure 3.2 from “Half adders and full adders”

Set 4 bits. Make A = 0001 and B = 0001 and step: the first column is a half adder. Now try A = 0111, B = 0001 and watch the carry ripple through three columns. Then turn on carry in. Fill in the eight-row full adder table in your notebook from what you see.

The adder stepper shows two 4-bit numbers as rows of bit buttons and reveals one column at a time from the right, giving each column's carry in, sum and carry out. Adding 0111 and 0001, the carry ripples through three columns to give 1000. The full adder table for A B Cin from 000 to 111 is Cout S = 00, 01, 01, 10, 01, 10, 10, 11.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. How do you make NOT from a single NAND?

  • Connect one input to 0
  • Connect both inputs to the signal
  • Connect one input to the output

Check it in “Everything from NAND”

2. How many NAND gates does the classic XOR construction use?

Answer: gates

Check it in “Everything from NAND”

3. A half adder is built from…

  • Two ANDs
  • An XOR for the sum and an AND for the carry
  • An OR for the sum and a NOT for the carry

Check it in “Half adders and full adders”

4. For a full adder with A = 1, B = 1, Cin = 1, read Cout S as a 2-bit binary number. What is its value in decimal?

Answer:

Check it in “Half adders and full adders”

5. How many full adders does an 8-bit ripple-carry adder use (one per column)?

Answer: adders

Check it in “Half adders and full adders”

6. In a 2:1 multiplexer Y = ¬S·A + S·B, what does S = 0 do?

  • Outputs B
  • Outputs A
  • Outputs A AND B

Check it in “Multiplexers and decoders: choosing and pointing”

7. How many select lines does a multiplexer need to choose one of 16 inputs?

Answer: lines

Check it in “Multiplexers and decoders: choosing and pointing”

Engineering applications

Arithmetic units

Every processor's arithmetic logic unit contains adders built from the full adder in this chapter, with multiplexers choosing which result reaches the output.

Memory addressing

A decoder turns an address into exactly one active line, so one row of a memory responds. A 3-to-8 decoder picks one of 2^3 = 8 rows.

Summary

Glossary

NAND and NOR (universal gates)
NAND outputs 0 only when all inputs are 1; NOR outputs 1 only when all inputs are 0. Either one alone can build every other logic function.
Half adder
A half adder adds two single bits and gives a sum bit (A XOR B) and a carry bit (A AND B).
Full adder and ripple-carry adder
A full adder adds three bits (A, B and a carry in) to give a sum and a carry out. Chaining n of them, each carry out feeding the next carry in, makes an n-bit ripple-carry adder.
Multiplexer
A multiplexer passes one of several data inputs to a single output, chosen by a binary number on its select lines; 2^k inputs need k select lines.
XOR gate
An XOR gate outputs 1 when its inputs are different and 0 when they are the same.

Project: An all-NAND selector

Design a 2-to-1 multiplexer (output A when S = 0, B when S = 1) using only NAND gates. Count the gates, then check your design against the truth table for all eight input combinations.

Deliverables

  • A gate diagram using only NAND
  • The gate count
  • An eight-row truth table check

References

4. Binary arithmetic

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Hardware adds the way you were taught at school, one column at a time with a carry, but in base 2. This chapter writes long binary numbers compactly in hexadecimal, builds a ripple-carry adder from full adders, and introduces two's complement, the code that lets the same adder handle negative numbers. It ends with the cases where the answer no longer fits.

Figure 4.1. Three-bit two's complement on a wheel (described in words)

Eight patterns arranged on a circle: 000 is 0, 001 is 1, 010 is 2, 011 is 3, 100 is −4, 101 is −3, 110 is −2 and 111 is −1. Stepping clockwise adds one; the jump from 011 to 100 is where signed overflow happens.

Explanation

4.1 Binary and hexadecimal

A sensor datasheet says its ID register reads 0x6B. What number is that, and why would anyone write it that way?

Place values that double

In binary each place is worth twice the one to its right: 1, 2, 4, 8, 16, 32, 64, 128. 1011 = 8 + 0 + 2 + 1 = 11. To go the other way, take away the biggest power of 2 that fits and repeat: 13 = 8 + 4 + 1 = 1101.

How much fits

n bits make 2ⁿ patterns, holding 0 to 2ⁿ − 1. 4 bits: 0 to 15. 8 bits (a byte): 0 to 255. 16 bits: 0 to 65,535. Each extra bit doubles the range.

Hex: four bits per digit

Hexadecimal has 16 digits: 0–9 then A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Each hex digit is exactly four bits, so a byte is two hex digits: 0x6B = 0110 1011 = 6 × 16 + 11 = 107. 0xFF = 255. The '0x' just marks a number as hex.

Common mix-ups

4.2 Multi-bit addition and the ripple-carry adder

Adding 0111 + 0001 changes every single bit of the answer. How long does a circuit have to wait before it can trust the result?

By hand: right to left

Line the numbers up, start at the rightmost column and add the two bits plus any carry. Write the sum bit and carry the rest. 1011 + 0110: 1 + 0 = 1; 1 + 1 = 10 → 0 carry 1; 0 + 1 + 1 = 10 → 0 carry 1; 1 + 0 + 1 = 10 → 0 carry 1. Result 1 0001 = 17 = 11 + 6.

The ripple-carry adder

One full adder per column, each carry out wired to the next carry in. It is simple and small, but a column cannot be sure of its answer until the carry from the right has arrived, so the carry ripples across the whole adder.

Worst-case delay

Each gate takes a little time to settle. In the virtual computer's model the first column's carry is ready after 3 gate delays (XOR, AND, OR), and each further column adds 2. A 4-bit adder needs 3 + 2 × 3 = 9 delays; 32 bits would need 65. Faster designs, such as carry-lookahead, compute carries in parallel at the cost of more gates.

Common mix-ups

4.3 Overflow and negative numbers

In a 4-bit computer, 7 + 1 = −8. That is not a bug in the adder. So what is going on?

Unsigned overflow

k bits hold 0 to 2ᵏ − 1. If a sum is bigger, the extra bit leaves as carry out and the register keeps the sum minus 2ᵏ. 4-bit 1011 + 0110 = 11 + 6 = 17 → keeps 1 (0001), carry out 1. The carry out flag is how hardware reports unsigned overflow.

Two's complement

To store negatives, let the top bit be worth −2ᵏ⁻¹. In 4 bits the range becomes −8 to 7: 0111 = 7, 1000 = −8, 1111 = −1. To negate, invert every bit and add 1. The same adder circuit then adds signed numbers correctly, so subtraction is just adding a negative.

Signed overflow

If two numbers of the same sign give a result of the opposite sign, the true answer did not fit. 0111 + 0001 = 1000: 7 + 1 'became' −8. Adding a positive and a negative can never overflow.

Real consequences

In 1996 the first Ariane 5 rocket was lost less than a minute after launch when its guidance software converted a 64-bit floating-point value into a 16-bit signed integer and the value did not fit. Embedded engineers choose widths with headroom and test the edges.

Derivation: Why 'invert and add 1' gives −n
  1. In k bits, n plus its bitwise inverse ¬n is all 1s: for example 0101 + 1010 = 1111. So n + ¬n = 2ᵏ − 1.

  2. Add 1 to both sides: n + (¬n + 1) = 2ᵏ.

  3. A k-bit register cannot hold 2ᵏ: it wraps to 0. So in k-bit arithmetic n + (¬n + 1) = 0, which means ¬n + 1 behaves exactly like −n.

  4. Example, 4 bits: 5 = 0101, ¬5 = 1010, +1 = 1011. Check: 0101 + 1011 = 1 0000, which wraps to 0000. ✓

  5. Equivalently, the top bit is worth −2ᵏ⁻¹ instead of +2ᵏ⁻¹: 1011 = −8 + 2 + 1 = −5.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Binary and hexadecimal: example 1

Convert 0xC8 to binary and decimal.

Multi-bit addition and the ripple-carry adder: example 1

Add 0101 + 0011 by hand, showing carries.

Overflow and negative numbers: example 1

Write −3 in 4-bit two's complement and check by adding 3.

Interactive figures, in words

Figure 4.2 from “Overflow and negative numbers”

Set 4 bits. Add 1111 + 0001 and read the unsigned result and carry out. Then add 0111 + 0001 and read the signed view: why is 7 + 1 shown as −8? Find a pair of negative numbers whose sum looks positive. Switch to 8 bits and repeat one of your examples.

The adder stepper shows each number's unsigned and signed values. In 4 bits, 1111 + 0001 gives 0000 with a carry out: unsigned overflow. 0111 + 0001 gives 1000, which is 8 unsigned but −8 signed: signed overflow, because two positive numbers gave a negative result. In 8 bits the signed range is −128 to 127.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. What is binary 1011 in decimal?

Answer:

Check it in “Binary and hexadecimal”

2. What is 0x2A in decimal?

Answer:

Check it in “Binary and hexadecimal”

3. Add 0110 + 0111 (4-bit). Give the result as a decimal number.

Answer:

Check it in “Multi-bit addition and the ripple-carry adder”

4. Using the model 'first carry after 3 gate delays, then 2 more per extra bit', how many gate delays does an 8-bit ripple-carry adder need for its final carry?

Answer: delays

Check it in “Multi-bit addition and the ripple-carry adder”

5. In a 4-bit unsigned register, what is 1011 + 0110? Give the value the register holds, in decimal.

Answer:

Check it in “Overflow and negative numbers”

6. What is −5 in 4-bit two's complement? Give the bit pattern's unsigned value in decimal.

Answer:

Check it in “Overflow and negative numbers”

7. Which 4-bit two's complement addition overflows?

  • 0011 + 1110 (3 + −2)
  • 0101 + 0100 (5 + 4)
  • 1111 + 1111 (−1 + −1)

Check it in “Overflow and negative numbers”

Engineering applications

Reading memory dumps

Engineers read registers and memory in hexadecimal because each hex digit is exactly four bits: 0x2A is 0010 1010, which is 42.

Sensor arithmetic

A signed 16-bit reading spans −32768 to 32767. Adding two large positive readings can produce a negative result, so firmware checks for overflow or uses a wider type.

Summary

Glossary

Hexadecimal
Hexadecimal is base 16, using digits 0–9 and A–F. Each hex digit stands for exactly four bits, so two hex digits describe one byte.
Two's complement (signed integers)
Two's complement represents negative integers so that ordinary binary addition still works: the top bit has a negative place value, so an n-bit number ranges from −2^(n−1) to 2^(n−1) − 1.
Full adder and ripple-carry adder
A full adder adds three bits (A, B and a carry in) to give a sum and a carry out. Chaining n of them, each carry out feeding the next carry in, makes an n-bit ripple-carry adder.
Propagation delay
Propagation delay is the time a gate's output takes to respond to a change at its input. The slowest path between flip-flops, the critical path, sets the fastest safe clock.

Project: A safe 8-bit adder specification

Specify an 8-bit adder for signed sensor values that raises a flag on overflow. Give the flag's rule in terms of the two input sign bits and the result's sign bit, and test it on at least six cases, including both edges of the range.

Deliverables

  • The overflow rule as a Boolean expression
  • Six or more test cases with expected results
  • A note on what the firmware should do when the flag is raised

References

5. From silicon to switches

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Gates are made of transistors, and transistors are made of doped silicon. This chapter goes down a level: why silicon is a semiconductor, how adding small amounts of other elements creates p-type and n-type regions, how a MOSFET acts as a voltage-controlled switch, and how pairing two kinds of transistor (CMOS) builds gates that draw almost no current while they sit still.

Figure 5.1. A CMOS inverter (described in words)

A pMOS transistor connects the supply VDD to the output Y, and an nMOS transistor connects Y to ground. Input A drives both gates. When A is 0 the pMOS conducts and Y is 1; when A is 1 the nMOS conducts and Y is 0. Only one transistor is on at a time.

Explanation

5.1 Conductors, insulators and why silicon

Copper and glass differ in resistivity by about a hundred billion billion times. Silicon sits in between, and that is why your phone works.

Resistivity: a property of the material

Resistivity (ρ, in ohm-metres) says how strongly a material opposes current, whatever its shape. Copper is about 1.7 × 10⁻⁸ Ω·m, glass around 10¹² Ω·m. Conductors, semiconductors and insulators are three bands on that enormous scale.

Free carriers make the difference

Current needs charges free to move. In a metal, each atom lends electrons to a shared 'sea', so there are vast numbers of free carriers. In an insulator, electrons are tightly bound. The band picture says the same thing: to move, an electron must jump an energy gap, which is zero in metals, small in semiconductors (1.1 eV for silicon) and large in insulators (about 9 eV for glass).

Semiconductors can be tuned

In pure silicon, heat lifts a few electrons across the gap, so warming it lowers its resistance. Adding a few impurity atoms per million, called doping, supplies extra carriers and cuts resistivity by millions of times. N-type doping adds electrons; p-type creates 'holes'. Joining the two makes diodes and transistors.

Why silicon?

Silicon is the second most common element in Earth's crust (it is in sand). It grows a tough, insulating oxide layer that chipmakers use to build transistors. Its gap is wide enough to work reliably when hot, yet doping controls it precisely. Germanium came first, but heat frees too many of its electrons.

Common mix-ups

5.2 Doped silicon and the p–n junction

Pure silicon barely conducts. Add one phosphorus atom for every few million silicon atoms and it conducts thousands of times better. Why so dramatic?

Doping

Pure silicon has very few free charge carriers at room temperature. n-type silicon is doped with atoms like phosphorus (5 outer electrons), adding free electrons. p-type is doped with boron (3), adding holes: gaps that move like positive charges. Tiny amounts change conductivity enormously because pure silicon starts with so few carriers.

The junction

Where p meets n, electrons and holes near the boundary combine, leaving a thin depletion region with no free carriers and a built-in voltage across it. Push current forward (p positive) and, above about 0.6–0.7 V for silicon, the barrier collapses and current flows. Push in reverse and the depletion region widens: almost no current. That is a diode.

From junctions to transistors

A MOSFET has two n-type regions (source and drain) in p-type silicon. Normally the p–n junctions block current between them. A positive voltage on an insulated gate above the gap pulls electrons up into a thin channel that connects source to drain. No gate current flows: the gate's voltage alone opens the switch.

Common mix-ups

5.3 Building gates from switches

A modern chip has billions of transistors and almost all are wired as just three or four patterns. What are they?

Two kinds of switch

An nMOS conducts when its gate is high (1) and is good at pulling a node down to ground. A pMOS conducts when its gate is low (0) and is good at pulling up to VDD. In the switch-level model each is simply on or off; in reality each has some resistance and capacitance.

Pull-up and pull-down networks

A static CMOS gate has a pull-down network of nMOS between the output and ground and a pull-up network of pMOS between VDD and the output. Series nMOS = AND condition for pulling down; parallel nMOS = OR. The pull-up is the dual: series becomes parallel and vice versa. So NAND = series nMOS + parallel pMOS; NOR = parallel nMOS + series pMOS. Each input drives one of each: a 2-input gate has 4 transistors.

Why it costs so little to sit still

For every input combination exactly one network conducts. So in steady state there is no path from VDD to ground and only tiny leakage flows. Power is spent mainly when the output switches and its load capacitance charges or discharges, which is next lesson's topic.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Conductors, insulators and why silicon: example 1

How many powers of ten separate the resistivity of copper (1.7 × 10⁻⁸ Ω·m) from glass (10¹² Ω·m)?

Doped silicon and the p–n junction: example 1

A silicon diode and a 470 Ω resistor are in series with a 3.3 V supply. Estimate the current.

Building gates from switches: example 1

Design the transistor networks for a 3-input NOR.

Interactive figures, in words

Figure 5.2 from “Conductors, insulators and why silicon”

Start with copper, then step through every material and watch the marker jump along the resistivity scale. Pick pure silicon and raise the temperature from 20 °C to 100 °C. Then compare pure silicon with doped silicon at the same size. Which change made the bigger difference?

The materials explorer places eight materials on a resistivity scale from 10⁻⁹ to 10¹⁴ ohm-metres: copper, aluminium and nichrome in the conductor region; germanium, pure silicon and doped silicon in the semiconductor region; glass and rubber in the insulator region. Heating copper from 20 °C to 70 °C raises its resistance about 20%; heating pure silicon over the same range cuts its resistance by more than ten times. Doped silicon conducts millions of times better than pure silicon.

Figure 5.3 from “Building gates from switches”

Start with the inverter and toggle A. Then switch to NAND and NOR and try all four input combinations. For each, say which network conducts and confirm there is never a path from VDD to ground.

In the gate builder, the inverter's output is 1 when A = 0 (pMOS on) and 0 when A = 1 (nMOS on). The NAND output is 0 only for A = B = 1, when both series nMOS conduct; the NOR output is 1 only for A = B = 0, when both series pMOS conduct. In every case exactly one network conducts.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Pure silicon at room temperature is best described as…

  • A conductor
  • An insulator
  • A semiconductor

Check it in “Conductors, insulators and why silicon”

2. What does doping do to silicon?

  • Adds a few impurity atoms that supply extra charge carriers, lowering resistivity hugely
  • Coats it in metal so it conducts
  • Heats it permanently

Check it in “Conductors, insulators and why silicon”

3. Doping silicon with boron (3 outer electrons) makes…

  • n-type: extra electrons
  • p-type: holes that act as positive carriers
  • an insulator
  • a metal

Check it in “Doped silicon and the p–n junction”

4. A diode is reverse biased. What happens to the depletion region?

  • It disappears
  • It widens, so almost no current flows
  • It becomes a conductor
  • It moves to the n side only

Check it in “Doped silicon and the p–n junction”

5. A pMOS transistor conducts when its gate is…

  • 1 (high)
  • 0 (low)
  • floating
  • always

Check it in “Building gates from switches”

6. How many transistors are in a static CMOS 3-input NAND gate?

Answer: transistors

Check it in “Building gates from switches”

7. A student wires both networks of a gate so that, for input 11, both conduct. What happens?

  • The output is a perfect 1
  • A direct path from VDD to ground: large current, undefined output
  • Nothing: CMOS can't draw current
  • The gate becomes a NOR

Check it in “Building gates from switches”

Engineering applications

Battery-powered devices

Because a CMOS gate has no direct path from supply to ground once it has settled, a sleeping microcontroller can draw very little current. This is a large part of why a sensor node can run for a long time on a small battery.

Temperature sensing

A semiconductor's resistance changes strongly with temperature. Thermistors use this on purpose; chip designers must allow for it, because hotter silicon conducts and leaks differently.

Summary

Glossary

Diode forward voltage
A diode conducts in one direction once the voltage across it reaches its forward voltage, after which its voltage stays roughly constant whatever the current.
NOT gate (inverter)
A NOT gate has one input and outputs its opposite: 0 becomes 1 and 1 becomes 0.
NAND and NOR (universal gates)
NAND outputs 0 only when all inputs are 1; NOR outputs 1 only when all inputs are 0. Either one alone can build every other logic function.
Electrical power
The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.

Project: Transistor count for a NOR gate

Design a two-input CMOS NOR gate. Draw the pull-up and pull-down networks, explain why one is series and the other parallel, and check all four input cases to show the output is never connected to both supply and ground.

Deliverables

  • A transistor-level sketch
  • A four-row table of which transistors conduct
  • A sentence on why the design draws almost no static current

References

6. State machines and sequential logic

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Combinational logic forgets: its output depends only on the inputs right now. Real machines need memory. A finite-state machine remembers which state it is in and moves between states when events arrive. This chapter specifies state machines precisely, then builds the same machine twice: in hardware with flip-flops and a clock, and in software as a loop.

Figure 6.1. A two-state turnstile (described in words)

Two states, Locked and Unlocked. From Locked, a coin event moves to Unlocked and a push leaves it Locked. From Unlocked, a push moves back to Locked and a coin leaves it Unlocked. An arrow marks Locked as the starting state.

Explanation

6.1 States, events and guards

A delivery robot gets an order with 25 % battery left. Should it go, or charge first? Who decides, and where is that rule written?

The four ingredients

A state is a mode the robot can be in (IDLE, DRIVING). An event is something that happens (an order arrives, a bump sensor fires). A transition says: in this state, on this event, go to that state. A guard is a condition that must also be true, such as battery ≥ 30 %.

Guards split one event into cases

IDLE + order has two rules: battery ≥ 30 % → DRIVING, battery < 30 % → CHARGING. Together the guards cover every battery level exactly once. If they overlapped, two rules could fire and the result would depend on which is listed first; if they left a gap, some orders would vanish.

Ignored events

If no rule matches, the machine stays where it is. That is often right (a second order while driving), but it can hide a missing rule. Review each state and ask, for every event: should something happen here?

Common mix-ups

6.2 Specifying a state machine

A lock that opens only when you type 1-0-1 has to remember something between key presses. What is the least it needs to remember?

The ingredients

A finite-state machine has a set of states, a start state, inputs, outputs and a transition function next = f(state, input). In a Moore machine the output depends only on the state; in a Mealy machine it depends on the state and the current input (often fewer states, but outputs can glitch with the input).

The table is the design

A state-transition table lists, for every state and every input, the next state and the output. Every cell must be filled: an empty cell is an unhandled case, which in hardware means undefined behaviour. Name states by what they remember ('seen 10') rather than S2, and the table almost writes itself.

Overlaps and testing

In 1101, the pattern 101 ends at position 4 and its last 1 can start a new match. A correct detector, after finding 101, goes to the state that remembers '1' rather than back to the start. Because inputs are finite, short machines can be tested exhaustively: the designer checks all 510 strings up to 8 bits.

Common mix-ups

6.3 A state machine in hardware

Turn a state-transition table into a circuit and it is always the same shape: a register and a cloud of gates. Why that shape?

The template

State register: n D flip-flops holding the current state code. Next-state logic: combinational gates computing the next code from the current code and the inputs. Output logic: gates computing outputs from the state (Moore) or state and inputs (Mealy). On each rising clock edge the register loads the next state.

From table to equations

Give each state a binary code (S0 = 00, S1 = 01, S2 = 10). Rewrite the table as a truth table with inputs (Q1, Q0, x) and outputs (Q1⁺, Q0⁺). Each column is a Boolean function you can simplify and build from gates. For the 11 detector with this encoding: Q0⁺ = x·¬Q1·¬Q0, Q1⁺ = x·(Q1 + Q0), output = Q1.

Why a clock?

Between edges the gates settle; at the edge, every flip-flop samples together. So the circuit only ever moves from one well-defined state to the next, no matter how messy the gate delays are, as long as the logic settles before the next edge. That timing condition comes back in RTL design.

Common mix-ups

6.4 A state machine in software

The same traffic-light controller can be twelve gates and four flip-flops, or twenty lines of code in a loop. When would you choose each?

The super-loop pattern

One variable holds the state. A loop runs forever: read inputs, then switch (state); each case sets outputs, checks its exit conditions and, if one is true, assigns the next state and records the entry time. Nothing blocks, so the loop runs many times per second and every input is noticed promptly.

Timed states and guards

Most real machines leave a state on a timeout or an event. Store entered = now() when entering a state and test now() − entered ≥ duration. Guard conditions (only go to WALK if the button was pressed AND the all-red has finished) are the software version of AND gates in next-state logic.

Hardware or software?

Hardware FSMs react within one clock cycle and keep running if the processor crashes; they are fixed once built. Software FSMs are easy to change and log but react only as fast as the loop and depend on the code being correct. Safety systems often use both: software for normal control, a simple hardware or independent monitor that forces a safe state.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

States, events and guards: example 1

Battery 45 %. Events: order, arrived, done, order. Where does the robot end?

Specifying a state machine: example 1

Fill in the transition table for 'output 1 after an odd number of 1s'.

A state machine in hardware: example 1

Verify Q0⁺ = x·¬Q1·¬Q0 and Q1⁺ = x·(Q1 + Q0) for the 11 detector with S0 = 00, S1 = 01, S2 = 10.

A state machine in software: example 1

Sketch the super-loop for a two-state blinker: LED_ON for 200 ms, LED_OFF for 800 ms.

Interactive figures, in words

Figure 6.2 from “States, events and guards”

Load the complete design. Set the battery to 25 % and send: order, charged, order, arrived, done. Write the state after each event before you press it. Then load each 'Bug' design and read what the checker says.

The state-machine runner shows a table of rules: IDLE plus order goes to DRIVING if battery is at least 30 %, else CHARGING; DRIVING plus arrived goes to DELIVERING; DRIVING plus bump goes to FAULT; DELIVERING plus done goes to IDLE and costs 20 % battery; CHARGING plus charged goes to IDLE at 100 %; FAULT plus reset goes to IDLE. Sending events steps through the table.

Figure 6.3 from “Specifying a state machine”

Choose 'Detect 11' with 3 states and fill in the table until 'Check my machine' passes. Then try 'Detect 101' with 4 states. If a check fails, type the failing string into the input box and trace it.

One correct 11 detector: S0 (output 0) goes to S0 on 0 and S1 on 1; S1 (output 0) goes to S0 on 0 and S2 on 1; S2 (output 1) goes to S0 on 0 and stays in S2 on 1. One correct 101 detector uses four states meaning: nothing useful, seen 1, seen 10, seen 101 (output 1, goes to 'seen 10' on 0 and 'seen 1' on 1).

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Which pair of guards on IDLE + order is complete and non-overlapping?

  • battery > 30 and battery < 30
  • battery ≥ 30 and battery < 30
  • battery ≥ 30 and battery ≤ 30

Check it in “States, events and guards”

2. Which of these is an event rather than a state?

  • CHARGING
  • bump sensor triggered
  • FAULT

Check it in “States, events and guards”

3. In a Moore machine the output depends on…

  • Only the current input
  • Only the current state
  • The state and the current input
  • The clock frequency

Check it in “Specifying a state machine”

4. A state machine has 6 states. How many flip-flops does a binary state encoding need?

Answer: flip-flops

Check it in “Specifying a state machine”

5. A controller has 9 states with binary encoding. How many flip-flops?

Answer: flip-flops

Check it in “A state machine in hardware”

6. The same 9-state controller uses one-hot encoding. How many flip-flops?

Answer: flip-flops

Check it in “A state machine in hardware”

7. Why avoid long blocking delays inside a state machine's loop?

  • They use too much memory
  • Nothing else, including inputs, is checked while the delay runs
  • They make the code longer
  • Delays are illegal in C

Check it in “A state machine in software”

Engineering applications

Controllers you can test

Lifts, traffic lights, vending machines and communication protocols are written as state machines because a transition table can be checked arrow by arrow.

Hardware or firmware

The same state machine can live in flip-flops, reacting within one clock cycle, or in a software loop that is easier to change. The choice depends on how fast the machine must respond.

Summary

Glossary

D flip-flop
A D flip-flop stores one bit. On each rising clock edge it copies its D input to its Q output and holds that value until the next edge.
Registers
Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.
Propagation delay
Propagation delay is the time a gate's output takes to respond to a change at its input. The slowest path between flip-flops, the critical path, sets the fastest safe clock.

Project: A pedestrian crossing controller

Specify a controller for a single pedestrian crossing with a request button and a timer. Draw the states and transitions, list every event each state ignores, and describe how you would implement it in flip-flops and as a software loop.

Deliverables

  • A state diagram and transition table
  • A list of ignored events per state
  • The number of flip-flops for binary and one-hot encodings
  • A test sequence that visits every transition

References

7. Instructions and the datapath

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A processor is a state machine that reads its next job from memory. The instruction set architecture is the contract between software and hardware: which instructions exist, how they are encoded as numbers and what each one changes. This chapter encodes instructions, traces a short program cycle by cycle, and opens up the datapath and control unit that carry each instruction out.

Figure 7.1. An instruction is a number with fields (described in words)

An 8-bit instruction word split into a 4-bit opcode field and a 4-bit operand field, with the example 0001 1110: opcode 1 and operand 14. Below it, a loop of three boxes: fetch, then decode, then execute, then back to fetch.

Explanation

7.1 The contract between code and silicon

Code compiled years ago still runs on brand-new processors with completely different insides. What promise makes that possible?

What an ISA promises

An instruction set architecture defines: the registers visible to programs (Nibble has one, A, plus flags Z and C); the instructions and exactly what each does; their encoding as bits; how operands are found (addressing modes: a constant, a register, a memory address); and how memory and I/O look to software. Anything not in the contract is free for the hardware designer to change.

Architecture vs microarchitecture

Two chips implementing the same ISA can be utterly different inside: one takes 3 clock cycles per instruction, another overlaps many instructions in a pipeline. Both run the same program and get the same answers; only the speed differs. That separation is why software lasts longer than any one chip.

Design styles

Accumulator machines (like Nibble) keep one working register. Load–store / RISC machines (like RISC-V or the TV-16 teaching format) do arithmetic only between registers, with separate load and store instructions. CISC machines allow memory operands in arithmetic. Fewer, simpler instructions make hardware simpler; richer ones make programs shorter.

Common mix-ups

7.2 Instructions are just numbers

The hex number 0x1405 can be a price, a colour or an instruction that puts 5 into register 2. How does the processor know which?

Fields

An instruction word is divided into fields. TV-16 (a teaching format made for these lessons) uses 16 bits: opcode bits 15–12 (16 operations), rd bits 11–9 and rs bits 8–6 (registers R0–R7), and imm bits 5–0 (a constant 0–63). Nibble packs an opcode nibble and a 4-bit argument into 8 bits: word = opcode × 16 + arg.

Encoding and decoding

To encode, shift each field to its position and combine: word = opcode·2¹² + rd·2⁹ + rs·2⁶ + imm. LDI R2, 5 = 1·4096 + 2·512 + 0 + 5 = 5125 = 0x1405. To decode, shift right and mask: rd = (word >> 9) AND 7. In hardware, decoding is just wiring: each field's bits run straight to the circuits that need them.

Bits are a budget

Every field width is a trade-off. More opcode bits allow more instructions; more register bits allow more registers; more immediate bits allow bigger constants. A 16-bit word can't have all three. That is why real ISAs have several formats and why loading a large constant can take two instructions.

Common mix-ups

7.3 Tracing a program, counting cycles

Two programs give the same answer. One takes 12 clock cycles, the other 33. How do you know before you run them?

A trace table

List, for each instruction executed: the program counter, the instruction, and every register, flag and memory cell it changes. Only change what the instruction says it changes: STORE writes memory but leaves A and the flags alone. Most tracing mistakes are updating something an instruction doesn't touch.

Flags are how machines decide

Arithmetic sets flags as a side effect: Z (result was zero) and C (a carry fell off the top). A conditional jump like JNZ reads Z. In 'Count down', ADD 15 sets Z when A reaches 0; STORE in between doesn't disturb Z; JNZ then falls through to HALT.

Counting cycles

Cycles = Σ (instructions executed × cycles per instruction). A loop body of b instructions run n times costs b·n plus setup. In the stepper's model every instruction takes 3 cycles; real processors vary by instruction. The executed count, not the program length, decides speed: a 5-line loop can run thousands of instructions.

Common mix-ups

7.4 Thinking in register transfers

Can you swap two registers in one clock cycle without a spare? In software you need a temporary variable. In hardware you don't. Why?

The notation

A ← A + B means: on the next clock edge, register A loads the value of A + B computed from the current outputs. A condition can guard it: if LOAD: R ← D. Several transfers listed for the same cycle all happen together. RTL hides gate-level detail while keeping exact timing.

Same edge, old values

Every register's input is computed from the values before the edge, and every register loads at the edge. So A ← B and B ← A swap; A ← B and B ← (A + B) steps a Fibonacci pair (3, 5 → 5, 8). Software executes lines in order, so the same two lines would give a different answer: a classic bug when translating between the two.

Datapath building blocks

Registers hold values (with a load-enable). Multiplexers choose which value goes where. The ALU computes (add, subtract, AND…). Buses carry values between them. A control unit sets the multiplexer selects, ALU operation and load-enables each cycle, deciding which transfers happen.

Common mix-ups

7.5 The control unit is a state machine

A processor's datapath can add, store and jump, but it does nothing on its own. What tells each part when to act?

Fetch, decode, execute as RTL

In the stepper's model each instruction takes three cycles. Fetch: IR ← ROM[PC]. Decode: PC ← PC + 1 while the control unit reads the opcode. Execute: the opcode's own transfer, such as A ← A + M[a] with flags updated, or if Z = 0: PC ← a. Then back to fetch.

Control signals

Each transfer happens because control lines are on: rom_read and ir_load in fetch; pc_inc in decode; for ADD, ram_read, alu_add, a_load and flags_load. The control unit is an FSM whose state is the step (fetch, decode, execute) and whose outputs, depending on that state and the opcode, are these signals.

Hard-wired or microcoded

A hard-wired control unit computes the signals with gates. A microcoded one stores them in a small memory addressed by (opcode, step): each row is one cycle's control word. Microcode is easier to change and fix; hard-wired is faster. Ben Eater's breadboard computer uses EEPROMs as microcode.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

The contract between code and silicon: example 1

Write a Nibble program that sets M3 to M0 + M0.

Instructions are just numbers: example 1

Decode TV-16 word 0x2280.

Tracing a program, counting cycles: example 1

Trace 'Add two numbers' with M0 = 9, M1 = 8.

Thinking in register transfers: example 1

A = 2, B = 7. Each cycle: A ← A + B, B ← A. Find A and B after 2 cycles.

The control unit is a state machine: example 1

List the control signals for STORE 4 in each of its three cycles.

Interactive figures, in words

Figure 7.2 from “Instructions are just numbers”

Encode LDI R2, 5 and ADD R1, R2, 0 and write down their hex words. Then type A2C3 into the decoder and explain each field. Finally switch to the Nibble format and encode LOAD 2: why is it 0x12?

The encoder shows each bit of the word coloured by field. LDI R2, 5 encodes to 0x1405; ADD R1, R2, 0 to 0x2280; 0xA2C3 decodes to opcode 10 (ADDI), rd = 1, rs = 3, imm = 3. In the Nibble format LOAD 2 is opcode 1 and argument 2, so 0x12 = 18.

Figure 7.3 from “Tracing a program, counting cycles”

Run 'Add two numbers' to the end and record the cycle count and the carry. Then step through 'Count down' one instruction (three clicks) at a time, writing a trace table: line, instruction, A, Z, M0. Check your predicted cycle count.

The stepper runs 'Add two numbers' in 4 instructions (12 cycles), leaving M2 = 1 with C = 1. 'Count down' from 3 executes LOAD, three rounds of ADD 15, STORE 0, JNZ 1, then HALT: 11 instructions, 33 cycles, ending with M0 = 0 and Z = 1.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Which of these is NOT part of an ISA?

  • The list of instructions
  • The number of programmer-visible registers
  • How many clock cycles the cache takes on a miss
  • How instructions are encoded in bits

Check it in “The contract between code and silicon”

2. An ISA has a 6-bit opcode field. At most how many different operations can it encode?

Answer: operations

Check it in “The contract between code and silicon”

3. Encode TV-16 'LDI R2, 5' (opcode 1, rd 2, rs 0, imm 5) and give the word in decimal.

Answer:

Check it in “Instructions are just numbers”

4. TV-16's immediate field is 6 bits, unsigned. What is the largest constant LDI can load in one instruction?

Answer:

Check it in “Instructions are just numbers”

5. A straight-line program executes 6 instructions on a machine that takes 3 cycles per instruction. How many cycles?

Answer: cycles

Check it in “Tracing a program, counting cycles”

6. Why does A ← B, B ← A in one cycle swap correctly in hardware?

  • The hardware secretly uses a temporary register
  • Both registers sample their inputs at the same edge, from the old values
  • A updates first, then B
  • It doesn't; it gives A = B

Check it in “Thinking in register transfers”

7. In the stepper's model, what does the decode step change?

  • A
  • The flags
  • PC ← PC + 1
  • Memory

Check it in “The control unit is a state machine”

8. A microcoded machine has 16 opcodes, 4 steps per instruction and a 12-bit control word. How many bits of microcode ROM?

Answer: bits

Check it in “The control unit is a state machine”

Engineering applications

One program, many chips

Because the ISA is a contract, the same machine code runs on a small low-power core and on a large fast one. They differ in microarchitecture, not in what the instructions mean.

Firmware debugging

When a robot's controller misbehaves, engineers read the program counter and registers in a debugger. A trace table, like the ones in this chapter, is how they reason about what happened.

Summary

Glossary

Instruction set architecture (ISA)
The ISA is the contract between software and hardware: the instructions, registers, data types and addressing modes a processor promises to support.
Fetch–decode–execute cycle
A processor runs a program by repeatedly fetching the instruction at the program counter, decoding what it means, executing it and moving the program counter on.
Registers
Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
ALU (arithmetic logic unit)
The ALU is the part of a processor that performs arithmetic (add, subtract) and logic (AND, OR, XOR, shifts) on values from registers, and sets status flags such as zero and carry.
Address space
The address space is the range of addresses a processor can generate. With n address bits and byte addressing, it can reach 2^n bytes.

Project: Design an instruction format

Design an 8-bit instruction format for a tiny processor with 4 registers that needs at least 6 operations. Decide how many bits go to the opcode and to the operands, justify the trade-off, and encode a three-instruction program in your format.

Deliverables

  • A field diagram with bit counts
  • A table of opcodes
  • The encoded program in binary and hexadecimal
  • One thing your format cannot do, stated honestly

References

8. Performance and pipelining

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

How fast is a processor? The Iron Law splits the answer into three factors: instructions per program, cycles per instruction and time per cycle. This chapter finds what limits the clock period, then shows how pipelining overlaps instructions like an assembly line, and why hazards stop the overlap from ever being perfect.

Figure 8.1. Four instructions in a five-stage pipeline (described in words)

A grid with four instructions as rows and eight clock cycles as columns. Each instruction passes through IF, ID, EX, MEM and WB, starting one cycle after the one before. All four finish in 8 cycles instead of the 20 cycles they would take one after another.

Explanation

8.1 How fast can the clock tick?

Why can't a processor designer just set the clock to 100 GHz and make everything 25 times faster?

The critical path

Every path from a register output through gates to a register input must settle within one clock period. The longest one sets the clock. In a ripple-carry adder it is the carry rippling through every column: about 2 gate delays per bit, so a 32-bit ripple adder is roughly eight times slower than a 4-bit one.

Shortening it

Designers attack the critical path with faster circuits (carry-lookahead adders compute carries in parallel at the cost of more gates), or by pipelining: putting registers in the middle of a long path so each piece fits a shorter period. The clock speeds up; each operation now takes more cycles, but a new one can start every cycle.

More cycles or faster cycles?

Run time = cycles × T_clk. A single-cycle design does everything in one long cycle; a multi-cycle design (like the 3-step model in the stepper) uses several short ones. Which wins depends on how evenly the work splits: the iron law T = IC × CPI × T_clk keeps every trade-off honest.

Derivation: The register-to-register timing constraint
  1. At a clock edge the launching register's output changes after t_clk→Q.

  2. The new value travels through combinational logic; the slowest route, the critical path, takes t_logic.

  3. The capturing register needs its input stable for t_setup before the next edge.

  4. So the next edge must come no sooner than T_clk ≥ t_clk→Q + t_logic + t_setup, and f_max = 1/T_clk.

  5. Example: 0.2 + 10 × 0.1 + 0.1 = 1.3 ns, so f_max = 1/1.3 ns ≈ 769 MHz.

Common mix-ups

8.2 Single-cycle, multi-cycle and the Iron Law

Chip A runs at 4 GHz, chip B at 2 GHz. B finishes your program first. How?

Single-cycle datapath

Every instruction completes in one long clock cycle, so CPI = 1, but the cycle must be long enough for the slowest path (instruction memory → register read → ALU → data memory → register write, for a load). Simple instructions waste most of the cycle.

Multi-cycle datapath

Break execution into steps (fetch, decode, execute, memory, write-back) and give each step one short cycle. Instructions use only the steps they need, so CPI is now an average (perhaps 4) but the cycle is about the length of one step. Hardware can be reused across steps: one memory and one ALU instead of separate ones.

Three factors, coupled

A richer instruction set lowers IC but may raise CPI or the cycle time. A deeper pipeline shortens the cycle but raises CPI when hazards hit. A good comparison quotes all three and measures them on the same program, compiled the same way, which is why benchmark suites exist.

Derivation: The Iron Law, from units
  1. Time per program = (instructions / program) × (cycles / instruction) × (seconds / cycle).

  2. The units cancel: instructions × cycles/instruction × seconds/cycle = seconds. So T = IC × CPI × t_clk = IC × CPI / f.

  3. IC is set by the algorithm, the compiler and the instruction set. CPI by the microarchitecture (pipelining, caches, prediction). t_clk by the circuit and the process technology.

  4. Speed-up of B over A = T_A / T_B = (IC_A/IC_B) × (CPI_A/CPI_B) × (f_B/f_A).

  5. Example: A has IC = 10⁹, CPI = 2, 4 GHz: T = 0.5 s. B has IC = 0.8×10⁹, CPI = 1.1, 2 GHz: T = 0.44 s. B wins by 0.5/0.44 ≈ 1.14× despite half the clock.

Common mix-ups

8.3 Pipelining: an assembly line for instructions

A laundry takes 30 minutes to wash, 40 to dry and 20 to fold. How long do four loads take if you never wait for one to finish before starting the next?

Throughput versus latency

Pipelining does not make one instruction faster: it still passes through every stage, and register overhead makes it slightly slower. What improves is throughput: once full, the pipeline completes one instruction every cycle. Ideal CPI approaches 1 for long runs.

The classic five stages

IF fetches the instruction, ID decodes it and reads registers, EX uses the ALU, MEM accesses data memory, WB writes the result back. Registers between stages hold each instruction's state so the stages can work on different instructions at once.

Balance and overhead

The clock must suit the slowest stage, and every stage boundary adds a register's setup and clock-to-output delay. Deeper pipelines get diminishing returns and, as you will see, pay more for every hazard. Modern designs settle on roughly 10–20 stages as a compromise.

Derivation: How much faster can a pipeline be?
  1. Unpipelined: each instruction takes T, so n instructions take n·T.

  2. Split into k stages. If perfectly balanced, each stage is T/k, but each needs a pipeline register adding overhead o. Cycle = T/k + o.

  3. Pipelined time for n instructions = (k + n − 1)(T/k + o).

  4. Speed-up S = n·T / ((k + n − 1)(T/k + o)). As n → ∞, S → T/(T/k + o) = k / (1 + k·o/T).

  5. With no overhead the limit is k. With o = 0.1 T, a 5-stage pipe tops out at 5/1.5 ≈ 3.3×; a 20-stage pipe at 20/3 ≈ 6.7×, not 20×.

  6. Unbalanced stages are worse: the cycle is set by the slowest stage, so S ≤ T / max(stage delay).

Common mix-ups

8.4 Hazards, forwarding and branch prediction

An instruction needs a number the previous one hasn't finished computing. Does the whole assembly line stop?

Data hazards

A read-after-write hazard occurs when an instruction needs a register that an earlier, still-in-flight instruction will write. Without help, the reader stalls in ID until the writer reaches WB: 2 bubbles for adjacent instructions in the classic 5-stage pipe. Forwarding (bypassing) wires the ALU output straight back to the ALU input, removing the stall for ALU results.

The load-use stall

A load's data appears only at the end of MEM. Even with forwarding, an instruction that uses it immediately must wait one cycle. Compilers hide this by scheduling an independent instruction between the load and its use, which is why the 'Load then use' program in the pipeline diagram has an unrelated sub in the middle.

Control and structural hazards

A branch is not resolved until EX, so the pipeline has already fetched 2 instructions that may be wrong. Stalling on every branch wastes those cycles always; predict not taken wastes them only when the branch is taken; dynamic predictors learn each branch's habit and are right well over 90% of the time on typical code. A structural hazard arises when two stages need one resource, like a single memory port for fetch and data: hence separate instruction and data caches.

Hazards in the Iron Law

Every stall adds to CPI: CPI = 1 + (data stalls per instruction) + (branch fraction × mispredict rate × penalty) + (memory stalls). Deeper pipelines raise the branch penalty, so a faster clock can lose to a shorter pipe with a better predictor.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

How fast can the clock tick?: example 1

A 16-bit ripple adder has 2 gate delays per bit plus 1, at 0.08 ns each, between registers with t_cq = 0.15 ns and t_su = 0.1 ns. Find f_max.

Single-cycle, multi-cycle and the Iron Law: example 1

A mix is 50% ALU (4 steps), 20% loads (5), 10% stores (4), 20% branches (3). Step time 200 ps. Compare with an 800 ps single-cycle design.

Pipelining: an assembly line for instructions: example 1

Stages of 200, 150, 250, 300 and 100 ps, register overhead 20 ps. Find the cycle time and the speed-up for many instructions versus the 1000 ps unpipelined design.

Hazards, forwarding and branch prediction: example 1

lw r1, 0(r2) then add r3, r1, r4, with forwarding. Stalls?

Hazards, forwarding and branch prediction: example 2

Branches are 15% of instructions; a predictor is wrong 8% of the time; the penalty is 3 cycles. Extra CPI?

Interactive figures, in words

Figure 8.2 from “Pipelining: an assembly line for instructions”

Choose 'Independent ALU ops', turn forwarding on and choose 'Perfect predictor'. Read the diagonal staircase and check the cycle count against k + n − 1. Then pick the other programs to see the ideal break: that is next lesson's topic.

The pipeline table has one row per instruction and one column per clock cycle; each instruction's IF, ID, EX, MEM and WB cells shift one column to the right of the previous instruction's, forming a staircase. For 5 independent instructions it ends at cycle 9.

Figure 8.3 from “Hazards, forwarding and branch prediction”

Every stall cycle adds to CPI, and this calculator shows how much. Set branches to 20%, mispredict to 10% and penalty to 2: read the CPI. Raise the penalty to 15 (a deep pipeline) and watch the branch slice grow. Pin a design, then trade a faster clock for a bigger penalty and read the speed-up.

The Iron Law calculator shows CPI as base + branch stalls + memory stalls. With 20% branches, 10% mispredicted at 2 cycles, and 30% memory instructions missing 5% at 40 cycles, CPI = 1 + 0.04 + 0.6 = 1.64, and T = IC × CPI ÷ f.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. t_clk→Q = 0.2 ns, logic = 1.0 ns, t_setup = 0.1 ns. What is f_max, in MHz (nearest whole number)?

Answer: MHz

Check it in “How fast can the clock tick?”

2. What sets the maximum clock frequency of a synchronous design?

  • The shortest register-to-register path
  • The longest register-to-register path (the critical path)
  • The number of registers
  • The supply voltage only

Check it in “How fast can the clock tick?”

3. A program executes 750 million instructions with an average CPI of 0.8 on a 2 GHz processor. How long does it take, in milliseconds?

Answer: ms

Check it in “Single-cycle, multi-cycle and the Iron Law”

4. Design A: CPI 1.6 at 3 GHz. Design B: CPI 1.0 at 2.4 GHz, same instruction count. What is B's speed-up over A?

Answer: ×

Check it in “Single-cycle, multi-cycle and the Iron Law”

5. 127 instructions run on a 4-stage pipeline. Hazards insert 6 stall cycles in total. How many clock cycles until the last instruction completes?

Answer: cycles

Check it in “Pipelining: an assembly line for instructions”

6. A 1,200 ps datapath is split into 6 perfectly balanced stages with 50 ps register overhead each. What is the speed-up limit for very long programs?

Answer: ×

Check it in “Pipelining: an assembly line for instructions”

7. lw r5, 4(r2) / add r6, r5, r1. Which hazard and, with forwarding, how many stall cycles?

  • Structural, 0
  • Data (load-use), 1
  • Control, 2
  • Data, 0 thanks to forwarding

Check it in “Hazards, forwarding and branch prediction”

8. On the classic 5-stage pipeline with no forwarding, a chain of 4 ALU instructions each uses the previous one's result. How many total cycles? (Ideal is 8.)

Answer: cycles

Check it in “Hazards, forwarding and branch prediction”

Engineering applications

Comparing processors fairly

A higher clock frequency does not guarantee a faster program: if the faster clock needs more cycles per instruction, the Iron Law can come out worse. Engineers compare time for the same program.

Real-time control

A control loop must finish within its sample period every time. Pipeline stalls and branch mispredictions make timing vary, so real-time systems often measure worst-case time, not average time.

Summary

Glossary

Pipelining
Pipelining splits instruction execution into stages and overlaps them, so that while one instruction executes the next is being decoded and the one after is being fetched.
Pipeline hazards and forwarding
A hazard is a situation where the next instruction cannot proceed on schedule. Data hazards happen when an instruction needs a result an earlier one has not finished producing.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.
Amdahl's law
Amdahl's law says the overall speed-up from improving part of a task is limited by the fraction of time that part takes.
Propagation delay
Propagation delay is the time a gate's output takes to respond to a change at its input. The slowest path between flip-flops, the critical path, sets the fastest safe clock.

Project: Pipeline or not?

A single-cycle design has a 10 ns critical path. Splitting it into five stages adds 0.5 ns of register overhead per stage, and 20 % of instructions stall for one cycle. Estimate the time per instruction for both designs and decide whether pipelining pays, showing every step.

Deliverables

  • The pipelined clock period with the overhead included
  • The average CPI with stalls
  • Time per instruction for both designs and the speed-up
  • One assumption that could change your answer

References

9. The memory hierarchy

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A processor can work far faster than main memory can supply data. Caches close the gap by keeping recently and nearby used data in small, fast storage close to the processor. This chapter explains why programs show locality, how an address is split into tag, index and offset, and how to measure the result with the average memory access time.

Figure 9.1. The memory hierarchy and AMAT (described in words)

A stack of levels from top to bottom: registers, L1 cache, L2 cache, main memory, storage. An arrow on one side says smaller and faster towards the top; an arrow on the other says larger and slower towards the bottom. Below: AMAT = hit time + miss rate × miss penalty, for example 1 + 0.05 × 100 = 6 cycles.

Explanation

9.1 Locality and the memory hierarchy

Two loops add up the same million numbers. One is ten times slower. Same chip, same maths. What is different?

The hierarchy

Registers (bytes to a few KB, under a nanosecond), L1 cache (tens of KB, about 1 ns), L2/L3 (hundreds of KB to tens of MB, several to tens of ns), DRAM (GB, around 100 ns), flash or disk (TB, microseconds to milliseconds). Each level is bigger, slower and cheaper per byte than the one above. Typical figures vary widely between chips.

Temporal locality

Data used now is likely to be used again soon: loop counters, a filter's coefficients, the top of the stack. Keeping recently used data in a small fast memory serves those repeat visits.

Spatial locality

Data near what you just used is likely to be used next: the next array element, the next instruction. Caches move whole blocks (often 64 bytes) so one miss pre-loads the neighbours. Walking a 2-D array row by row in a row-major language uses this; walking it column by column wastes it.

Common mix-ups

9.2 Inside a cache: tags, sets and ways

A cache holds a tiny fraction of memory. When the CPU asks for address 0x1F40, how does the cache know in one nanosecond whether it has it?

Offset, index, tag

With B-byte blocks, the lowest log₂ B bits are the offset (which byte in the block). With S sets, the next log₂ S bits are the index (which set to look in). The remaining high bits are the tag, stored with the block and compared on every access. Sets S = cache size ÷ (block size × ways).

Direct-mapped versus set-associative

Direct-mapped (1 way): each block has exactly one possible line. Fast and simple: one tag comparison. N-way set-associative: each set holds N blocks, so N comparisons happen in parallel and a multiplexer picks the hit way. Conflict misses fall; area, energy and sometimes hit time rise. Fully associative is one set holding everything.

Replacement and writes

When a set is full, LRU (least recently used) evicts the block untouched for longest; real caches often approximate it. Stores need a policy too: write-through sends every write to the next level; write-back marks the block dirty and writes it only on eviction, saving bandwidth.

The hardware cost

Each way needs a tag-width equality comparator: one XNOR per bit plus an AND tree, and a valid bit. A 4-way cache with 18-bit tags needs 4 × 18 = 72 XNORs before the AND trees and way multiplexer. That is the area and energy behind 'just add associativity'.

Common mix-ups

9.3 Average memory access time

A cache hits 95% of the time. Is that good? It depends entirely on what the other 5% cost.

One formula, three levers

AMAT = hit time + miss rate × miss penalty. Reduce hit time (small, simple L1), reduce miss rate (bigger, more associative, better prefetching) or reduce miss penalty (an L2, faster memory, critical-word-first). They fight: bigger and more associative usually means slower hits.

Local and global miss rates

L2's local miss rate looks bad (20–50% is common) because L1 has already filtered out the easy accesses. What matters for AMAT is the global rate m₁·m₂, often well under 1%.

Back to the Iron Law

Memory stalls add to CPI. A program with 0.3 memory accesses per instruction and 1.5 extra cycles per access from misses gains 0.45 CPI: as much as many branch-prediction improvements. This is why memory is often called the bottleneck.

Derivation: AMAT for two levels, and back into CPI
  1. One level: every access pays h₁; a fraction m₁ also pays the penalty P₁. AMAT = h₁ + m₁P₁.

  2. With L2, an L1 miss is served by L2, whose own average time is h₂ + m₂·t_mem, where m₂ is L2's local miss rate (misses ÷ accesses that reach L2).

  3. So P₁ = h₂ + m₂·t_mem and AMAT = h₁ + m₁(h₂ + m₂·t_mem).

  4. Global L2 miss rate = m₁·m₂: the fraction of all accesses that reach memory.

  5. Memory stall cycles per instruction = (memory accesses per instruction) × (AMAT − h₁), if the hit time is already counted in base CPI.

  6. Example: h₁ = 1, m₁ = 0.05, h₂ = 10, m₂ = 0.2, t_mem = 100: AMAT = 1 + 0.05 × 30 = 2.5 cycles, versus 6 without L2.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Locality and the memory hierarchy: example 1

A C program sums a 1000×1000 int matrix as sum += a[j][i] (column by column). Why is it slow, and what is the fix?

Inside a cache: tags, sets and ways: example 1

A 32 KB direct-mapped cache, 64 B blocks, 32-bit addresses. Split the address.

Inside a cache: tags, sets and ways: example 2

Same cache made 2-way. What changes?

Average memory access time: example 1

Option A: 1-cycle L1, 6% miss rate. Option B: 2-cycle L1, 3% miss rate. Both backed by a 40-cycle L2 that never misses. Which is better?

Interactive figures, in words

Figure 9.2 from “Locality and the memory hierarchy”

Run 'Walk an array', then 'Small loop, twice', then 'Big stride', all direct-mapped with 16 B blocks. For each, predict the hit rate before you press Show all. Then try 32 B blocks on the array walk and on the stride.

The cache simulator lists each address, its set and tag, and whether it hits. With 16-byte blocks: walking 32 integers gives 8 misses and 24 hits; reading 16 integers twice gives 4 misses; a 64-byte stride misses every time.

Figure 9.3 from “Average memory access time”

Start with L2 off. Raise main-memory latency and watch AMAT climb. Turn L2 on and find the L2 miss rate at which it stops being worth having. Which change saves more: halving the L1 miss rate, or halving the L2 hit time?

The AMAT explorer shows a stacked bar: L1 hit time, plus L1 misses times L2 time, plus global misses times memory time. With h₁ = 1, m₁ = 5%, h₂ = 10, m₂ = 20% and memory 100 cycles, AMAT = 2.5 cycles; without L2 it is 6.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?

  • Temporal
  • Spatial only
  • Neither
  • Only compulsory misses

Check it in “Locality and the memory hierarchy”

2. A loop reads 256 consecutive 4-byte floats into an empty cache with 64-byte blocks. How many misses?

Answer: misses

Check it in “Locality and the memory hierarchy”

3. A 32 KB 4-way set-associative cache has 16-byte blocks and 64-bit byte addresses. How many offset bits are there?

Answer: bits

Check it in “Inside a cache: tags, sets and ways”

4. How many single-bit XNOR gates do the tag comparators of an 8-way cache with 20-bit tags need?

Answer: XNORs

Check it in “Inside a cache: tags, sets and ways”

5. A cache has a hit time of 3 cycles, a miss rate of 1% and a miss penalty of 100 cycles. What is the AMAT in cycles?

Answer: cycles

Check it in “Average memory access time”

6. L1 miss rate is 4% and L2 local miss rate is 25%. What percentage of all accesses go to main memory?

Answer: %

Check it in “Average memory access time”

7. Base CPI is 1. There are 0.4 memory accesses per instruction, L1 hit time is included in base CPI, and AMAT is 3 cycles with a 1-cycle hit time. What is the effective CPI?

Answer:

Check it in “Average memory access time”

Engineering applications

Faster image processing

Looping over an image row by row reads neighbouring bytes, so each cache block fetched is fully used. Looping column by column can touch a new block on almost every read and run much slower on the same data.

Embedded memory budgets

Small microcontrollers may have no data cache at all, so their designers place time-critical data in on-chip memory instead. Knowing the hierarchy tells you where each variable should live.

Summary

Glossary

Memory hierarchy and caches
Computers use a hierarchy of memories from tiny fast registers and caches to large slow main memory and storage; a cache keeps recently used data close to the processor.
Average memory access time (AMAT)
Average memory access time is the cache hit time plus the miss rate multiplied by the miss penalty.
RAM, flash and EEPROM
RAM is fast, volatile working memory that loses its contents without power; flash and EEPROM are non-volatile and keep data, but are slower to write and wear out after many write cycles.
Address space
The address space is the range of addresses a processor can generate. With n address bits and byte addressing, it can reach 2^n bytes.

Project: Size a cache for a sensor log

A controller reads a 4 KiB log sequentially, again and again. Compare a 1 KiB and an 8 KiB cache with 16-byte blocks: estimate the miss rate of each on repeated passes and the AMAT with a 1-cycle hit time and a 50-cycle miss penalty. Explain the difference using locality.

Deliverables

  • Miss-rate estimates for both caches with reasoning
  • AMAT for both
  • A one-paragraph recommendation

References

10. Power, performance and the chip

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Every design decision in this book ends up on a die of silicon that costs money, uses energy and gets hot. This chapter brings the threads together: where a chip's power goes, why lowering the voltage helps so much, how designers trade power, performance and area, and how wafers, lithography and yield set what a chip costs.

Figure 10.1. The power, performance, area triangle (described in words)

A triangle with corners labelled Power, Performance and Area. Inside: dynamic power P = α·C·V²·f. A note shows that halving the supply voltage V at the same frequency cuts dynamic power to one quarter.

Explanation

10.1 Where a chip's power goes

Halve a processor's supply voltage and its switching power drops by three quarters. Why the square?

Static and dynamic

Static power is leakage: P_static = V·I_leak, small per transistor but significant with billions of them and rising with temperature. Dynamic power is the cost of switching: P ≈ αCV²f. In most busy logic, dynamic power dominates.

The four knobs

Lower α by not switching what you don't need (clock gating). Lower C with smaller transistors and shorter wires. Lower f when there is less work. Lower V for the biggest win, because it is squared, but transistors switch more slowly at low voltage, so f must fall too.

Voltage and frequency scaling

Since lower V forces lower f, reducing both together cuts power roughly with V³ while performance falls only with f. Phones run in a ladder of (V, f) operating points and jump between them many times per second. Energy per operation, CV², falls with V²: slow-and-low is efficient.

Derivation: Dynamic power P ≈ αCV²f
  1. A gate's output drives a load capacitance C. Charging it from 0 to V through the pMOS draws charge Q = CV from the supply at voltage V: energy taken = QV = CV².

  2. Half of that, ½CV², ends up stored on the capacitor; the other half is lost as heat in the pMOS.

  3. Discharging through the nMOS dumps the stored ½CV² as heat. So one full 0 → 1 → 0 cycle costs CV² from the supply.

  4. If the node completes such a cycle on a fraction α of clock cycles (the activity factor), at clock frequency f, cycles per second = αf.

  5. Power = energy per cycle × cycles per second: P = αCV²f. Summed over all nodes, C is the total switched capacitance.

Common mix-ups

10.2 Power, performance, area: the chip designer's triangle

Why would a chip designer use four slow cores instead of one fast one, when one fast core is simpler?

The three letters

Power: dynamic (switching) plus static (leakage, which flows even when nothing switches and grows with temperature and with the number of transistors). Performance: work per second, roughly cores × frequency × operations per cycle. Area: silicon used, which sets cost and yield. Improving one usually costs another.

Why parallelism saves energy

Two cores at half the clock deliver the same throughput as one core at full clock. Each can then run at a lower voltage, and power ∝ V²·f. Same work, less power, double the area. This is why phones use many slower cores and why GPUs have thousands. It only works if the task can be split: serial parts don't speed up.

Where it stops paying

Leakage scales with the amount of silicon and with V, not with f. Add many cores at very low voltage and leakage starts to dominate; area and cost grow too. Below a certain voltage the transistors become too slow and too variable. The best design is a sweet spot, and it moves with the workload and the process technology.

Dynamic voltage and frequency scaling

Chips change V and f on the fly: high when you need speed, low when idle. Because energy per operation ∝ V², 'race to idle' (run fast, then sleep) and 'run slow and low' compete; which wins depends on how much leakage the chip has while active and asleep.

Derivation: Where α·C·V²·f comes from
  1. A logic gate's output drives a load capacitance C. Charging it from 0 to V through the supply draws charge Q = C·V at voltage V: energy C·V² leaves the supply.

  2. Half of that, ½CV², is stored in the capacitor; the other half is dissipated as heat in the pull-up transistor. Discharging dumps the stored half as heat in the pull-down. So each full 0 → 1 → 0 cycle costs C·V².

  3. If a fraction α of the chip's capacitance switches each clock cycle (the activity factor), energy per cycle is α·C·V².

  4. At f cycles per second: P_dyn = α·C·V²·f.

  5. Higher f needs faster transistors, which need higher V (gate delay falls as V rises above the threshold voltage). So pushing f up drags V up, and power grows roughly like f³ near the top of the range.

  6. Energy per operation is P/throughput = α·C·V²·f/(f·ops per cycle) = α·C·V²/(ops per cycle): it depends on V², not on f. Lower voltage is the lever for energy efficiency.

Common mix-ups

10.3 Inside an integrated circuit

A processor die the size of a fingernail holds billions of transistors and kilometres of wire. How is something that complex designed at all?

Die, cells and rows

The die is the rectangle of silicon that becomes one chip. Digital logic is built from a standard-cell library: pre-designed, pre-characterised gates and flip-flops (NAND2, INV, DFF, …) of equal height, placed in rows like bricks so their power rails line up. Memories (SRAM macros), analogue blocks and I/O pads around the edge complete the floorplan.

Interconnect

Cells are joined by many layers of metal interconnect (often 10 or more) separated by insulator and linked by vias. Lower layers are thin and dense for short local wires; upper layers are thick for long routes, power and clock. Wire delay grows roughly with the square of length for an unbuffered RC wire, so long nets are split with repeater buffers.

Clock distribution

Every flip-flop must see the clock edge at nearly the same moment. A clock tree (or mesh) of buffers fans the clock out from one source to millions of flip-flops. The difference in arrival times is skew; it eats into the time available for logic. The clock network switches every cycle, so it can take a large share of dynamic power, which is why designers clock-gate idle blocks.

The design flow

Engineers write RTL (register-transfer level code), simulate it, synthesise it into a netlist of standard cells, then place and route it, check timing (every path must fit in the clock period), power and manufacturing rules, and finally send the layout to the fab. Each step trades power, performance and area (PPA).

Common mix-ups

10.4 Wafers, lithography and yield

A wafer full of chips comes out of the fab. Some dies work and some don't, and the bigger the chip, the worse the odds. Why?

From sand to wafer

Ultra-pure silicon is grown as a single crystal ingot and sliced into polished wafers, today usually 300 mm across. Each wafer carries hundreds of copies of the chip, called dies, side by side.

Photolithography, layer by layer

A light-sensitive photoresist is spun on, exposed through a patterned mask (reticle) with deep-ultraviolet or extreme-ultraviolet light, and developed. The exposed pattern then guides etching, deposition of new material, or doping (implanting atoms to change conductivity). Repeating this for dozens of layers builds transistors at the bottom and metal wiring above. A process node (for example '7 nm' or '3 nm') names a technology generation; the number no longer equals any single physical dimension.

Test, dice, package

Finished wafers are probed: each die is tested electrically and failures are marked. The wafer is diced, good dies are packaged (bonded to a substrate with pins or balls) and tested again. Defects (a particle, a lithography error) kill dies at random, which is what the yield model captures.

Why area is expensive

Bigger dies mean fewer per wafer and lower yield, so cost per good die grows faster than area. Edge loss adds to it: square dies can't tile a circle. That is why designers fight for area, why the same design gets cheaper as a process matures and D falls, and why chiplets split a big design into several small, high-yield dies.

Derivation: Where e^(−D·A) comes from
  1. Assume killer defects land independently and uniformly on the wafer, D per cm² on average.

  2. Then the number of defects k on one die of area A follows a Poisson distribution with mean λ = D·A.

  3. P(k) = λ^k e^(−λ) / k!. A die works only if k = 0, so Y = P(0) = e^(−D·A).

  4. Example: D = 0.1 /cm², A = 100 mm² = 1 cm²: Y = e^(−0.1) ≈ 90.5%. At 4 cm², Y = e^(−0.4) ≈ 67%.

  5. Good dies per wafer = DPW × Y, with DPW ≈ π(d/2)²/A − πd/√(2A). Cost per good die = wafer cost ÷ (DPW × Y).

  6. Real defects cluster, so fabs often use the negative-binomial model, which gives higher yield for large dies than Poisson. The trend is the same.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Where a chip's power goes: example 1

A block has C = 2 nF switched capacitance, α = 0.15, V = 1.2 V, f = 500 MHz. Find P, then P at 0.9 V and 375 MHz.

Power, performance, area: the chip designer's triangle: example 1

A core uses 2 W at 1.0 V and 1.5 GHz. Estimate the dynamic power at 0.8 V and 1.0 GHz (if timing allows).

Inside an integrated circuit: example 1

A register-to-register path has clock-to-Q 50 ps, logic 600 ps, wire 150 ps, setup 40 ps and skew 30 ps. What is the maximum clock frequency?

Wafers, lithography and yield: example 1

300 mm wafer, 100 mm² dies, D = 0.1 /cm², wafer cost $10,000 (illustrative). Cost per good die?

Wafers, lithography and yield: example 2

Same wafer, 400 mm² dies?

Interactive figures, in words

Figure 10.2 from “Power, performance, area: the chip designer's triangle”

Meet the brief (≥ 3 GOPS, ≤ 0.6 W, ≤ 10 mm²). Start with one core and push the clock: what stops you? Then try 2, 4 and 8 cores, lowering f and V each time. Which core count gives the lowest energy per operation, and why does 8 cores lose?

The explorer uses a simplified CMOS model with sliders for supply voltage, clock frequency, core count and activity factor. It reports dynamic power, leakage, throughput, area and energy per operation, and checks a brief of at least 3 GOPS within 0.6 W and 10 mm². One core can't reach 3 GOPS because the maximum clock at 1.3 V is about 1.9 GHz. Two cores need about 1.0 V and use about 0.76 W, failing the power cap. Four cores at about 0.65 V and 0.75 GHz pass with about 0.46 W and 8.4 mm². Eight cores fail on area, and leakage dominates their power.

Figure 10.3 from “Wafers, lithography and yield”

Fix the defect density at 0.1 per cm² and sweep die area from 20 to 600 mm². Watch yield and cost per good die. Then fix the area at 400 mm² and halve the defect density: how much cheaper does each die get?

The explorer draws a circular wafer tiled with square dies, defects as random dots, and dies with a defect shown in red (also counted in text). For 300 mm, 100 mm² dies and 0.1 defects/cm², the formula gives 640 dies, yield 90.5% and about 579 good dies.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. α = 0.1, C = 1 nF, V = 1.0 V, f = 1 GHz. What is P = αCV²f, in watts?

Answer: W

Check it in “Where a chip's power goes”

2. Halving V (with α, C, f unchanged) changes dynamic power by a factor of…

  • 1/2
  • 1/4
  • 1/8
  • 2

Check it in “Where a chip's power goes”

3. A chip's dynamic power is P = α·C·V²·f. At 1 V and 1500 MHz it uses 5 W. The designers change the supply to 0.9 V and the clock to 3000 MHz (same α and C). What is the new dynamic power, in watts? (3 significant figures.)

Answer: W

Check it in “Power, performance, area: the chip designer's triangle”

4. In the PPA explorer, 8 cores at 0.5 V use more total power than 4 cores at 0.65 V for the same throughput. Why?

  • Dynamic power is higher with 8 cores
  • Leakage grows with the amount of silicon, and at very low voltage it dominates
  • The explorer is wrong
  • More cores always use more power

Check it in “Power, performance, area: the chip designer's triangle”

5. Why are standard cells all the same height?

  • So they look tidy
  • So they can be placed in rows sharing power and ground rails
  • Because transistors are all the same size
  • To make them slower

Check it in “Inside an integrated circuit”

6. An unbuffered wire 1 mm long has 20 ps delay. Using the RC model (delay ∝ L²), what is the delay of a 3 mm wire?

Answer: ps

Check it in “Inside an integrated circuit”

7. With a Poisson yield model Y = e^(−D·A), what percentage of 20 mm² dies work when the defect density is 0.3 defects per cm²?

Answer: %

Check it in “Wafers, lithography and yield”

8. With D = 0.2 /cm², what is the yield (as a percentage) of one 6 cm² monolithic die? (Four 1.5 cm² chiplets would each yield 74%.)

Answer: %

Check it in “Wafers, lithography and yield”

Engineering applications

Phones and laptops

Dynamic voltage and frequency scaling lowers V and f when the workload is light. Because dynamic power scales with V², a modest voltage drop saves a large share of power.

Why big chips cost more

Defects land on a wafer at random, so a larger die is more likely to contain one. Fewer dies fit and a larger share of them fail, which is one reason designers split big systems into smaller chiplets.

Summary

Glossary

Electrical power
The power transferred in a component is the voltage across it multiplied by the current through it. For a resistor this can also be written I²R or V²/R.
Propagation delay
Propagation delay is the time a gate's output takes to respond to a change at its input. The slowest path between flip-flops, the critical path, sets the fastest safe clock.
Clock speed, cycles and CPI
Execution time equals the number of instructions times the average cycles per instruction (CPI) divided by the clock frequency.

Project: A battery budget for a sensor chip

A sensor chip's logic switches C = 100 pF effectively (α·C) at 1.2 V and 10 MHz. Compute its dynamic power, then compute it again at 0.9 V and 5 MHz. Decide whether the slower setting still meets a task that needs 2 million cycles every second, and state what you have ignored.

Deliverables

  • Dynamic power at both settings with units
  • Whether each setting meets the cycle requirement
  • A list of the simplifications in your model (leakage, memory, sensors)

References

Known limitations