A one-bit ALU: AND, OR, XOR and ADD on a two-bit opcode
An ALU computes several things at once and then throws away all but the one you asked for. That sounds wasteful and is exactly right: gates are cheap, and choosing after the fact is faster than deciding first. 48 NAND gates.
Set A and B, pick an operation with OP1/OP0, and read OUT:
OP1 OP0 | operation |
|---|---|
0 0 | A AND B |
0 1 | A OR B |
1 0 | A XOR B |
1 1 | A + B + CIN — COUT carries |
CIN and COUT only mean anything for the add. Chain them and you have a
multi-bit ALU: the carry-out of each bit feeding the carry-in of the next.
The selection tree
Open ALU-1 and you will find all four results computed unconditionally — an
AND, an OR, an XOR and a full ADDER, all running all the time. Three
MUX-2 blocks then pick one: the first chooses between AND and OR, the second
between XOR and ADD, and the third chooses between those two pairs using
OP1.
That is a 4-to-1 multiplexer built as a tree of 2-to-1s, and it is the standard
shape. A multiplexer is itself just gates — (A AND NOT SEL) OR (B AND SEL) —
so the whole opcode mechanism is the same NANDs as everything else.
Things worth trying
- Set the opcode to add with
CINhigh and both inputs high:OUTis 1 andCOUTis 1, because 1 + 1 + 1 is binary 11. - Now drop
CINand compare AND against ADD with both inputs still high. The AND gives 1; the add gives 0 with a carry out. Same inputs, different meaning entirely. COUTis not gated by the opcode — it is the adder’s carry whatever operation you select, so it only means anything in add mode.
Built out of NAND gates and nothing else. The sandbox, the JSON module format and the rest of the library are described in Digital logic — from NAND to a computer.