Sikau

How computers work · Day 9 · about 45 min

Project: A 4-bit ALU

One unit that adds, subtracts and does logic, with zero, negative and carry flags.

The calculator inside the CPU

The ALU (arithmetic logic unit) is where the work happens: give it two numbers and an operation, get a result plus flags — was it zero? negative? did it carry? The CPU uses those flags to decide what to do next. Build one from your adder.

Subtraction reuses the adder

There's no separate subtraction circuit. a − b equals a + (−b), and in two's complement −b is NOT b plus one. So the ALU flips b's bits and feeds the adder a carry-in of 1. One adder, one row of NOT gates and a control bit handle both operations — exactly how real CPUs do it.

function sub4(a, b) {
  const notB = ~b & 0b1111;
  return add4(a, notB, 1);
}
console.log(sub4(9, 3));

The rest of this lesson

  • Computing the flagsexplain
  • One unit, many operationsexplain
  • Flag meaningsmatch
  • Flipping four bitspredict
  • Build the ALUchallenge
  • Badge quizquiz
  • Unit 2 completerecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work