# How a Computer Works: From a NAND Gate to a CPU

**TL;DR:** A whole working computer can be built from one kind of logic gate. I read the book that shows how, gave a talk about it, and this post walks the path from a single NAND gate to a CPU, with C code you can run.

I recently read *But How Do It Know? The Basic Principles of Computers for Everyone* by J. Clark Scott (2009) and gave a 15-minute talk about it to my team. This post is the written version, with everything from the talk in one place.

I found the book through [The Montana Mini-Computer](https://www.youtube.com/watch?v=zFhOn5Mc_rQ), a conversation between Casey Muratori and Carson Gross on Casey's YouTube channel. In it, Carson explains that he uses this book in a class he teaches at Montana State University.

The book builds a complete computer on paper, starting from one tiny part. You don't need any electronics background. If you can flip a light switch and add 8 + 5, you can follow it. I write code every day, and the book still filled gaps I didn't know I had.

Here's the path we'll take: bits → one gate → memory → the bus → RAM → the ALU → the clock → instructions → jumps → the outside world. Then we'll answer the question in the title.

## The Thermos joke

The book's title is the punch line of an old joke. A salesman is showing off a new invention, the Thermos bottle:

> "It keeps hot food hot, and cold food cold…"

Joe, standing in the crowd, can't hold it in any longer:

> "But how do it know?"

Joe imagined a sensor, a heater and a fridge inside the bottle, deciding what to do. The truth is much simpler. Heat always moves from hot to cold, and the Thermos only slows that down. It doesn't know anything about your soup.

We do the same with computers. We see what they can do and imagine something complicated inside. The book sets out to show that the real principle is simple.

**The short answer:** a CPU runs a program by fetching instructions from memory and carrying them out one step at a time. The rest of this post shows how those steps work in a simple 8-bit computer built from NAND gates.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/90398923-581e-4218-aaf5-d5c6d521da31.jpg align="center")

## The secret is speed

A computer can only do a few very simple things, and only one at a time. It looks complex because it does a huge number of those simple things, one after another, very fast.

Electricity in a wire moves at roughly half the speed of light: about three and a half times around the Earth in one second. The book makes a back-of-the-envelope estimate. If each simple step needs the electricity to travel about a foot, that's **500 million steps per second**. For comparison, a desk fan spinning 40 times a second would need about 145 days, almost five months, to turn 500 million times. (The book says six months, but the math comes out closer to five.)

Computers have become faster, smaller and cheaper since the 1940s. What they actually do has barely changed.

## Only one kind of thing: the bit

If you opened a computer and looked inside with a microscope, you wouldn't find any letters, numbers or pictures. There is only one kind of thing in there: the **bit**.

A bit is anything that can be in one of two states, like a light that is on or off, or a coin that shows heads or tails. Put 8 bits together and you have a **byte**, which has 256 possible on/off patterns.

A pattern means nothing by itself. Take this byte:

```text
0100 0001
```

In the ASCII code it's the letter `A`. Read as a binary number it's `65`. The bits are exactly the same in both cases. The meaning comes from a code that people agreed on.

A few more ASCII codes:

| Character | Binary | Decimal |
| --- | --- | --- |
| `A` | `0100 0001` | 65 |
| `B` | `0100 0010` | 66 |
| `a` | `0110 0001` | 97 |
| `0` | `0011 0000` | 48 |
| space | `0010 0000` | 32 |

## The crazy room: the NAND gate

This is my favorite part of the book. Imagine walking into a sunny room where the ceiling light is on, and you want to turn it off. There are two switches by the door, and both are already off. You flip one: nothing happens. You flip the other: nothing. You start flipping both wildly, and the light goes out at the moment **both switches are on**.

One switch off means the light is on. Both switches on means the light is off. It's a weird room, but it works exactly like the most basic part of a computer: the **NAND gate** (short for "Not AND"). Two bits go in, one bit comes out.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/56a874c0-3315-4c3e-ae5b-3f99b3381398.png align="center")

*The crazy room as a NAND gate: with both switches on, the light goes off.*

| Switch A | Switch B | Light |
| --- | --- | --- |
| off | off | **on** |
| off | on | **on** |
| on | off | **on** |
| on | on | off |

The gate doesn't decide anything. It is simply wired so that electricity comes out unless both inputs are on.

Here is the surprising claim of the book: **this is the only part you need.** Every other piece of the computer it builds is NAND gates wired together.

## Every other gate is just NANDs

Tie both inputs of a NAND together and you get **NOT**: on becomes off, off becomes on. Put a NOT after a NAND and you get **AND**. OR and XOR take a few more NANDs.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/b4e13ae2-257b-4689-95ff-0d90c382c7f1.png align="center")

*Left: NOT made from one NAND. Right: AND made from a NAND followed by a NOT.*

As developers, we can check this in a few lines of C. Save this as `gates.c`:

```c
#include <stdio.h>
#include <stdbool.h>

bool NAND(bool a, bool b) { return !(a && b); }

/* Everything below is built only from NAND */
bool NOT(bool a)         { return NAND(a, a); }
bool AND(bool a, bool b) { return NOT(NAND(a, b)); }
bool OR(bool a, bool b)  { return NAND(NOT(a), NOT(b)); }
bool XOR(bool a, bool b) {
    bool n = NAND(a, b);
    return NAND(NAND(a, n), NAND(b, n));
}

int main(void) {
    printf("a b | NAND AND OR XOR\n");
    printf("----+----------------\n");
    for (int a = 0; a <= 1; a++) {
        for (int b = 0; b <= 1; b++) {
            printf("%d %d |  %d    %d   %d  %d\n",
                   a, b, NAND(a, b), AND(a, b), OR(a, b), XOR(a, b));
        }
    }
    return 0;
}
```

Compile and run it:

```bash
gcc gates.c -o gates && ./gates
```

Output:

```text
a b | NAND AND OR XOR
----+----------------
0 0 |  1    0   0  0
0 1 |  1    0   1  1
1 0 |  1    0   1  1
1 1 |  0    1   1  0
```

One function, and every other gate falls out of it. From here on, every box in this post is NAND gates and wires.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/d7e9e968-1ff4-49b1-b005-1fbf4eec7982.png align="center")

## How four NAND gates store one bit

So far every gate just reacts to its inputs. To build a computer, we need something that **remembers**.

The book wires four NAND gates together so that the output loops back into the inputs. The result has an input `i`, an output `o`, and a third wire `s` for "set":

- While `s` is on, the output follows the input.
- When `s` turns off, the output **keeps the last value**, no matter what happens to the input.

That's one bit of memory. The loop is the whole trick.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/6e681991-bd42-45ff-84d6-861117c3c64a.png align="center")

*One bit of memory made from four NAND gates.*

From there, the book builds up step by step:

- **Byte:** 8 memory bits that share one `s` wire, so they're set together.
- **Enabler:** 8 AND gates that share one `e` ("enable") wire. When `e` is off, nothing gets out. When it's on, the byte's bits pass through.
- **Register:** a byte plus an enabler. You can write to it (set) and read from it (enable).

## The bus: 8 wires everyone shares

A computer needs to move bytes between registers. The book connects every register to the same 8 wires, called the **bus**.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/5db7ba33-4fef-4894-a3e4-92af2485f80e.png align="center")

*Copying R1 into R4: one enable, one set.*

To copy register R1 into R4:

1. Turn on R1's **enable**. Its byte appears on the 8 bus wires.
2. Turn R4's **set** on and off. R4 captures the byte.

That's it: one enable plus one set equals one copy. Only one register may enable at a time, or the bits collide. When you write `mov r4, r1` in assembly, this is what's happening underneath.

## RAM: 256 bytes, one address each

**RAM** (Random Access Memory) in the book is 256 registers arranged in a 16 × 16 grid.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/7eace52a-9a14-4f4a-829f-df4e23c1498f.png align="center")

*The address register feeds two decoders that select one spot in a 16 × 16 grid.*

How you pick one byte out of 256:

- The **MAR** (Memory Address Register) holds the address you want, from 0 to 255.
- Two decoders turn the first 4 bits into one of 16 rows and the last 4 bits into one of 16 columns.
- The byte where that row and column cross gets connected to the bus. Then you read it (enable) or write it (set) like any register.

Two things here are worth slowing down for. First, an address is a byte, and so is the content. That means a byte in RAM can hold the address of another byte, which is exactly what a pointer is. Second, "random access" means any address takes the same time to reach.

The book's RAM is tiny because its MAR is only 8 bits. With 32 bits you could address 4 GB. Same idea, bigger numbers.

## The ALU: 8 tricks with bytes

The **ALU** (Arithmetic and Logic Unit) is where bytes get changed. It takes two bytes in (A and B) and produces one byte out, which goes into a register called the **accumulator** (ACC).

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/a6de5188-8aa0-4eb3-8fdc-5f4fc9ef7e3b.png align="center")

*The ALU: inputs A and B, an operation code, the result in ACC, and four flags.*

Three "operation" bits choose what it does:

| Bits | Operation | What it does |
| --- | --- | --- |
| 000 | ADD | Adds A and B |
| 001 | SHR | Shifts the bits right |
| 010 | SHL | Shifts the bits left |
| 011 | NOT | Flips every bit |
| 100 | AND | Bit-by-bit AND |
| 101 | OR | Bit-by-bit OR |
| 110 | XOR | Bit-by-bit XOR |
| 111 | CMP | Compares A and B |

The ALU also produces four extra bits called **flags**: **C**arry (a bit fell off the end, like a sum over 255 or a shift), **A** larger, **E**qual, and **Z**ero. Remember these flags. They become every `if` statement you have ever written.

There's no subtract, multiply or divide in this hardware. Programs build them: subtraction is NOT plus ADD plus 1, and multiplication is shifts and adds.

## The clock and the stepper

All these parts need to act in the right order. That's the job of the clock and the stepper.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/d943e445-1f49-45eb-a590-ef9726d98bd3.png align="center")

*Top: the clock signals. Bottom: the stepper turning clock ticks into steps 1 to 6.*

The **clock** is a bit that turns on and off by itself, over and over. (A modern CPU's clock does this billions of times per second. That's what "GHz" means.) From it, the book makes two timing signals:

- **clk e**, a longer window when a register can be **enabled** onto the bus.
- **clk s**, a short pulse in the middle of that window when another register is **set**.

That ordering means the data on the bus is stable before anyone grabs it.

The **stepper** turns clock ticks into numbered steps: step 1, step 2, up to step 6, then back to 1. Each step does one bus transfer: one enable and one set. The clock is the heartbeat; the stepper is the choreography.

## How a CPU fetches and runs instructions

At this point the wiring does the same thing every time the stepper goes around. The book calls the fix "the first great invention": **store instructions in RAM, next to the data.**

Two new registers make it work:

- **IAR** (Instruction Address Register) holds the address of the next instruction. Today we call it the program counter.
- **IR** (Instruction Register) holds the instruction being executed. Its bits decide which enables and sets fire during the next steps.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/17476a21-0365-439f-b4d3-ab9cfb0c5e8d.png align="center")

*The CPU: registers, ALU, IAR, IR, MAR and RAM, all on one bus, run by the control section.*

Every trip through the stepper now does this:

- **Steps 1 to 3, fetch:** copy the instruction at address IAR from RAM into IR, and add 1 to IAR.
- **Steps 4 to 6, execute:** do whatever the bits in IR say.

Then it repeats, forever. A series of bytes in RAM that gets executed this way is a **program**. Code and data are the same stuff: bytes.

## How JUMP and JUMP IF make loops and decisions

The clock is fast and RAM is small. Without something new, the CPU would run off the end of RAM in a fraction of a second.

**Invention #2, JUMP:** an instruction that writes a new address into the IAR. The next instruction comes from somewhere else. Now we can **loop**.

**Invention #3, JUMP IF:** a jump that only happens if one of the ALU flags (Carry, A larger, Equal, Zero) is on. Now we can **decide**.

Here's a small program in the book's instruction language that counts to 5. (The labels `loop` and `done` are my shorthand for RAM addresses.)

```text
       DATA R0, 0000 0000   ; counter = 0
       DATA R1, 0000 0001   ; step    = 1
       DATA R2, 0000 0101   ; limit   = 5
loop:  CLF                  ; clear the flags
       ADD  R1, R0          ; R0 = R0 + R1
       CMP  R0, R2          ; is R0 equal to R2?
       JE   done            ; #3: jump if Equal
       JMP  loop            ; #2: jump back
done:  ...
```

In C, that's:

```c
int r0 = 0;
do { r0 += 1; } while (r0 != 5);
```

Every `if`, `for`, `while` and function call you've ever written ends up as jumps and flags like these.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/bd5d4e5f-8055-47fb-8976-1e00d4d74eed.jpg align="center")

## Ta daa! The machine's entire language

Put it all together and you get the complete instruction set of the book's computer. This table is the only language the machine "understands": its **machine language**.

| Code | Instruction | What it does |
| --- | --- | --- |
| `1000 rarb` | `ADD RA,RB` | RB = RA + RB |
| `1001 rarb` | `SHR RA,RB` | RB = RA shifted right by one bit |
| `1010 rarb` | `SHL RA,RB` | RB = RA shifted left by one bit |
| `1011 rarb` | `NOT RA,RB` | RB = RA with every bit flipped |
| `1100 rarb` | `AND RA,RB` | RB = RA AND RB, bit by bit |
| `1101 rarb` | `OR RA,RB` | RB = RA OR RB, bit by bit |
| `1110 rarb` | `XOR RA,RB` | RB = RA XOR RB, bit by bit |
| `1111 rarb` | `CMP RA,RB` | Compares RA with RB and sets the flags; stores nothing |
| `0000 rarb` | `LD RA,RB` | RB = the RAM byte at the address in RA |
| `0001 rarb` | `ST RA,RB` | Writes RB into RAM at the address in RA |
| `0010 00rb` | `DATA RB,xxxx xxxx` | RB = the byte right after this instruction |
| `0011 00rb` | `JMPR RB` | Continue at the address in RB |
| `0100 0000` | `JMP Addr` | Continue at the address in the next byte |
| `0101 caez` | `JCAEZ Addr` | Like JMP, but only if one of the tested flags is on |
| `0110 0000` | `CLF` | Turns all flags off |

`ra` *and* `rb` *pick one of four registers (R0 to R3).* `caez` *picks which flags to test.* `xxxx xxxx` *is any 8 bits, stored in the byte after the instruction.*

Plus `IN` and `OUT` for talking to devices, which we'll get to next.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/b15acc61-7867-4655-a0af-8f20c116a8ea.png align="center")

*One small part of the control section: how* `ADD R1, R2` *becomes enables and sets.*

The diagram above shows one small part of the control section: the gates that run an ADD instruction. Each gate combines "this is an ALU instruction" with one stepper step, and turns on the right enable and set. The whole control section is many of these, built only from AND and OR gates.

As the book puts it: *"Believe it or not, everything you have ever seen a computer do, is simply the result of a CPU executing a long series of instructions such as the ones above."*

## The outside world and software

A computer that can't talk to anyone isn't much use. The book adds an **I/O bus** and two instructions, `IN` and `OUT`, to talk to devices:

- **Keyboard:** pressing a key gives the CPU an ASCII byte.
- **Screen:** a section of display RAM where each bit is one pixel, scanned onto the screen over and over.
- **Disk:** bytes stored on a spinning surface and read or written by a moving head.

Your phone, your car and a cash register are all the same thing inside: a CPU and RAM. Only the devices around them differ.

Software fits in the same picture. The hardware is fixed: NAND gates and wires. Software is the bytes we put in RAM. Operating systems, compilers, file systems and your favorite framework are all just programs, and in the end they all run as instructions from that table.

The book also confesses: "I lied, sort of." The only parts that aren't made of NAND gates are converters between analog and digital, for things like sound and color brightness.

The book's computer is tiny: 8 bits, 256 bytes of RAM, no tricks for speed. Real computers are wider and faster, but as the author says, *"Real computers have things that this one does not, but they are not capable of doing things that this computer cannot do."*

## So… how do it know?

Back to Joe and his Thermos. After all of this, how does a computer know anything?

The book's answer, word for word: **"It doesn't know anything!"**

A NAND gate just reacts to electricity, or the lack of it, on its inputs. If one gate knows nothing, then a million of them wired together also know nothing.

We say a computer "knows", "remembers", "sees" or "decides". That's fine as shorthand, as long as we remember what's really happening underneath. The book ends with a chapter on philosophy, asking whether the brain and the mind are the same thing. It leaves that question open, and so will I.

> ![](https://cdn.hashnode.com/uploads/covers/6b03fe24bb5c907449b9075f/d4e68514-2f60-4ef3-8d7e-5c35d6a21cd5.jpg align="center")

## Takeaways

**Run the gates yourself.** Compile `gates.c`, then try building XOR a different way using only `NAND`. Ten minutes of tinkering will make the idea stick better than rereading the section.

**Look for the jumps in your own code.** Compile a small loop with `gcc -S`, or paste it into [Compiler Explorer](https://godbolt.org). Your `if` and `while` turn into a compare and a conditional jump, just like the count-to-5 program above. Here is the C loop from earlier, compiled with `gcc -S -O0 -masm=intel`:

```text
.L2:
        add     DWORD PTR -4[rbp], 1    ; r0 += 1
        cmp     DWORD PTR -4[rbp], 5    ; compare r0 with 5
        jne     .L2                     ; jump back if not equal
```

**Think of a pointer as a byte holding an address.** When pointers or references get confusing, picture the book's RAM. An address is a byte, the content is a byte, so one byte can hold the location of another. That's all a pointer is.

If you write code for a living, read this book. It's about 170 pages, you can finish it in a weekend, and you'll never look at a CPU the same way.

## Where to go next

If this post made you curious about what happens underneath your code, follow these two people:

- **Casey Muratori** runs [Computer, Enhance!](https://www.computerenhance.com), home of his Performance-Aware Programming course. It shows how modern CPUs actually run your code: assembly, caches, SIMD and multithreading. Most of the course is for paid subscribers, and some videos are free. He also posts on his YouTube channel, [Molly Rocket](https://www.youtube.com/@MollyRocket).
- **Carson Gross** teaches computer science at Montana State University and created [htmx](https://htmx.org). He co-wrote the book [Hypermedia Systems](https://hypermedia.systems) and wrote [The Grug Brained Developer](https://grugbrain.dev). His talks are worth watching if you care about keeping software simple.

A good place to start is the conversation where I found this book: [The Montana Mini-Computer (feat. Carson Gross)](https://www.youtube.com/watch?v=zFhOn5Mc_rQ).
