Programmer Calculator · snowch.github.io

From gates to a compiled if

Nine short pages that start with logic gates you can tap and end with an if statement compiled to ARM, traced flag by flag. Each page answers the question the one before it raises.

What this is

These pages grew out of one person's notes while learning how a processor handles signed and unsigned numbers. They are kept short, every claim is drawn as bits or gates you can change, and nothing is simulated behind the scenes: the pages compute their values in the open and light the drawing to match.

They are about real machines. The assembly is ARM, the types are C's, and where x86 differs it says so. If you would rather build a machine of your own from gates to a running program, the Digital Design course does that, with a simulator and graded projects. These notes are the companion that reads the machines you will actually meet.

A third track, Assembly Lab, is being written: you drive a real processor's instruction set one instruction at a time, with the C each instruction came from beside it.

You need: binary and hex, and the truth tables of NOT, AND, OR and XOR. Nothing else is assumed; each page introduces what it uses.

Reading order

  1. From gates to an ALU
    One full adder from five gates, four of them chained, and why the carry ripples. Tap the inputs and watch the gates work.
  2. From adding to subtracting
    Why 3 − 5 comes out as 0xFE and why that is right: the wheel of 256 patterns, negation as NOT then add 1, the borrow read off the carry, and the method on paper.
  3. Two readings: drills
    Six short exercises on the idea everything else assumes: one pattern is two numbers. Read, write, find, step, negate and judge, at 4 bits first.
  4. Where C meets the wheel
    Ten small C programs that go wrong at the edge of the range, stepped through in ARM with the registers and flags drawn before and after.
  5. Bit Lab: the ALU and its flags
    A miniature ALU drawn as gates, thirteen operations, and the N Z C V flags built from the result. Exercises, a quiz, and a breadboard build.
  6. From gates to a register
    The other half of a CPU: how the same kinds of gates are made to remember. A latch, a clock, and the 4-bit register the lab's flags live in.
  7. Signed or unsigned: who decides?
    The hardware stores no sign. Every ARM branch on one compare, then a real if in C beside the assembly a compiler emits, traced for any pair.
  8. From bytes to registers
    Why a byte has to be widened to fill a 32-bit register, what LDRB and LDRSB write into the spare bits, and the widened compare cell by cell.
  9. Flag drills
    Randomised predict-then-check exercises: the flags of a CMP, which branches fire, recovering a type from compiled code, widening by hand.

Part 6 is the one you can read out of order: nothing after it depends on it, and part 5 only needs its first paragraph, which it repeats.

Tools alongside