Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 57 ยท Projects

Project: A 4-bit ALU with Register File

Combine a ripple-carry adder, a multiplexer, status flags and a register file into a tiny 4-bit datapath, run a program on it and test it against a reference model.

This project pulls the course together. You will build a small datapath: an arithmetic logic unit that adds, subtracts and does bitwise work on 4-bit numbers, plus a register file that holds four values between operations. Then you will feed it a short program and prove it correct with a test harness. Nothing here is new theory; every part is something you have already met, wired into a working whole.

The design follows how real hardware is organized: a ripple-carry adder does the arithmetic, a multiplexer picks which result leaves the ALU, a decoder chooses which register is written, and flip-flop based registers remember the result. If you want the theory behind the ALU itself, see Designing an ALU.

The parts we will wire together

Adder Four chained full adders, with carry in.
Output mux Picks one of eight results with a 3-bit opcode.
Flags Zero, negative, carry and overflow.
Register file Four 4-bit registers, two read ports, one write port.
1 / 2

The ALU

The ALU takes two 4-bit inputs a and b and a 3-bit opcode, and produces a 4-bit result plus four flags. Eight operations fit in three opcode bits:

Opcode Name Result
0 ADD a + b
1 SUB a - b
2 AND a & b
3 OR a | b
4 XOR a ^ b
5 NOT ~a (4 bits)
6 SHL a shifted left one place
7 SHR a shifted right one place (logical)

Subtraction does not need a separate circuit. As you saw in two's complement, a - b equals a + ~b + 1. So for SUB the ALU inverts every bit of b (four XOR gates driven by a "subtract" control line) and sets the adder's carry in to 1. The same adder then serves both operations.

Every operation is computed all the time; the output multiplexer simply selects one result. That is how hardware works: nothing is "skipped", the unused results are just not routed to the output.

The flags describe the result:

  • Z (zero): all four result bits are 0.
  • N (negative): the top bit of the result, the sign bit when you read it as two's complement.
  • C (carry): the carry out of the adder. After SUB it means "no borrow", so C = 1 when a >= b as unsigned numbers.
  • V (overflow): the carry into the top bit XOR the carry out of it, which signals signed overflow.

Our ALU reports C and V only for ADD and SUB and clears them for logic operations, a common simplification. The program below prints a few operations, then checks ADD and SUB for all 256 input pairs against Python's own arithmetic, including the flag rules.

Python The 4-bit ALU with flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the first line of the output: 5 + 3 = 8 reads as 1000, which is -8 in 4-bit two's complement, so N and V are both 1. The two flags agree here, but they answer different questions. Also notice the third line: 5 - 5 gives zero, so Z = 1, and C = 1 because no borrow was needed.

The register file

An ALU alone is a calculator with no memory. A register file stores a few values so one result can feed the next operation. Ours has four registers, R0 to R3, each 4 bits wide. It needs three kinds of circuit:

  • Two read ports. Each is a 4:1 multiplexer that selects one register by its 2-bit address. Both can read at the same moment, so the ALU gets operands a and b together.
  • One write port. A 2:4 decoder turns the 2-bit destination address into four one-hot lines. Each line is ANDed with a write-enable signal, so at most one register loads on the clock edge.
  • Registers. Four groups of D flip-flops. Between clock edges they hold their value; on the edge, the selected one captures the new data.
flowchart LR
    RA["Read port A<br/>(4:1 mux)"] --> ALU["ALU"]
    RB["Read port B<br/>(4:1 mux)"] --> ALU
    ALU -- "result" --> WB["Write decoder<br/>+ enable"]
    ALU -- "flags" --> FL["Flag register"]
    WB --> REGS["R0 R1 R2 R3"]
    REGS --> RA
    REGS --> RB

One instruction: read two registers, compute, write the result back and update the flags.

The loop in the diagram is the point. The output of the registers feeds the ALU, and the output of the ALU feeds the registers. Because the registers only change on a clock edge, there is no uncontrolled feedback.

Running a program

An instruction names an operation, a destination register and its source registers. Executing one takes the same steps every time: read, compute, write back. We add one extra instruction, LDI (load immediate), which writes a constant straight into a register without using the ALU.

The program below multiplies 3 by 5 without a multiplier. Since 5 = 4 + 1, we shift 3 left twice (that is 3 * 4 = 12) and add 3 once more. It then loads 9 and subtracts, so you can watch the flags change. After the trace, the harness takes over.

Testing the machine

How do you know the whole thing is right? Hand-checking a few programs is a start, but hardware designers use a reference model: a slow, obviously correct version of the design, written with ordinary arithmetic. The harness then runs both on many inputs and compares everything, registers and flags.

The golden function below never touches the adder or the multiplexer. It uses Python's +, -, % and //. The harness runs four hand-written programs with known answers, then 500 random 12-instruction programs (with a fixed seed so every run is the same) and counts mismatches. A mismatch in a random program would point you at the exact sequence that breaks the design.

Python Register file, program and test harness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The trace shows the result R1 = 15 after the shift-and-add sequence, which is 3 * 5. The N flag is 1 because 1111 has its top bit set, even though the unsigned value 15 is perfectly valid: flags report on the bit pattern, and software decides which interpretation applies. The final subtraction 9 - 15 gives 1010, which is 10 unsigned (and -6 signed), with C = 0 because a borrow was needed.

When a randomized test fails, print the seed and the failing program. A reproducible failure is half the debugging work, which is why the harness fixes random.seed.

Ideas for extending it

You now have the skeleton of a processor's datapath. Try these steps, each of which uses ideas from later lessons:

  • Add a compare instruction that does a subtraction but skips the register write (set the write enable to 0), so only the flags change.
  • Add arithmetic shift right, which keeps the sign bit, and a rotate.
  • Widen everything to 8 bits by changing 4 to 8 in a few places and testing again.
  • Add a program counter and jumps that depend on the flags, and you have the tiny CPU.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does this ALU perform subtraction with the same adder it uses for addition?

    Two's complement negation is invert-and-add-one, so a - b equals a + ~b + 1. The XOR gates on b and the carry in make the adder do both jobs.
  2. 2. What does the output multiplexer of the ALU do?

    All operations are computed in parallel, and the 3-bit opcode drives a mux that routes exactly one result to the output.
  3. 3. In the register file, what is the decoder for?

    A 2:4 decoder activates exactly one of four lines, and each line gates the write enable of one register. Reads use multiplexers instead.
  4. 4. Why test the design against a separate reference model?

    The reference uses plain arithmetic instead of gate-level logic. When two independent implementations agree on thousands of inputs, confidence in the design is high; any disagreement shows where to look.

Summary

  • An ALU is an adder plus bitwise logic, with a multiplexer selecting the result; subtraction reuses the adder by inverting b and setting the carry in.
  • The flags Z, N, C and V summarize the result. Carry and overflow are separate: carry is for unsigned numbers, overflow for signed ones.
  • A register file is a write decoder, four registers and read multiplexers. Registers change only on the clock edge, so the ALU-to-register loop is safe.
  • Executing an instruction means read, compute, write back, and update the flags.
  • Test a design against an independent reference model on directed and seeded random cases.

Next: Practice: Combinational Logic.