Inside the ALU
The ALU, short for arithmetic logic unit, is the part of a CPU that does maths and logic. It reads two inputs from registers, small stores of bits. Here A = 0101, which is 5, and B = 0011, which is 3.
Inside are an adder and two logic units. All three get the same A and B and work at the same time: the adder makes 1000, the AND unit 0001 and the OR unit 0111.
So which answer comes out? A mux, short for multiplexer, is a switch that passes on just one of its inputs. A 2-bit operation code chooses it: 00 means ADD, 01 SUB, 10 AND and 11 OR.
Four operations
With the code at 00, the mux lets the adder's answer through. 0101 + 0011 = 1000, which is 8. The result lamps light, and the other two answers are simply not used.
Computers store negative numbers in two's complement: flip every bit, then add 1. So 3 = 0011 becomes 1100, plus 1 is 1101, which means −3. The ALU has an inverter on B and a carry-in for this.
Code 01 means SUB. B is inverted to 1100 and the carry-in is set to 1, so the same adder works out 5 + (−3): 0101 + 1100 + 1 = 1 0010. Four bits keep 0010, which is 2.
Code 10 picks the AND unit. Each output bit is 1 only where A and B both have a 1. 0101 AND 0011 = 0001. Only the last column has two 1s.
Code 11 picks the OR unit. Each output bit is 1 where A or B, or both, has a 1. 0101 OR 0011 = 0111. Same inputs, four codes, four different answers.
Status flags
Next to the result sit four flag lamps that describe it. To compare 5 with 5, the CPU subtracts: 0101 − 0101 = 0000. Every bit is 0, so the zero flag Z lights: the numbers are equal.
Now 3 − 5 = 1110, which is −2. The negative flag N copies the top bit: 1. The carry flag C is the adder's carry-out. Here it is 0, because 3 is smaller than 5 and the subtraction had to borrow.
Back to 5 + 3 = 1000. As signed numbers, 4 bits only reach 7, and 1000 reads as −8. Two positives gave a negative, so the overflow flag V lights: the signed answer is wrong.
The working
;; step 1/11 · inputs ;; about: Register A, Register B A = 0101 = 0·8 + 1·4 + 0·2 + 1·1 = 5 B = 0011 = 0·8 + 0·4 + 1·2 + 1·1 = 3 A register is a row of flip-flops that holds one number. Lit lamp = 1.
In a chip each bit is a high or low voltage on a wire; here a glowing lamp shows a 1. A lit wire with moving dashes is carrying the value the step is about. In Python, ~b & 0b1111 flips the four low bits of b, and &, | work bit by bit on whole numbers. Python's own integers never overflow; the 4-bit limit here is the width of the circuit.