The 2-to-1 mux
A multiplexer, or mux, works like a railway switch for data. Two inputs, A and B, come in and one output, Y, goes out. A select bit, S, sets the switch: it decides which input reaches Y.
S is 0. The NOT gate turns it into 1, which opens the top AND gate, so A = 1 gets through. The bottom AND gate gets S = 0, so it outputs 0. The OR gate passes the 1: Y = A.
Flip S to 1. Now the bottom AND gate is open and the top one is closed. Y copies B, which is 0, even though A is still 1. Only the select bit changed.
As logic: Y = (NOT S AND A) OR (S AND B). One AND gate is always closed, so the OR gate never mixes A and B. Watch all eight input rows: S = 0 always gives A, S = 1 always gives B.
Four inputs
With four inputs, one select bit is not enough. Two bits, S1 and S0, make four codes: 00, 01, 10 and 11, one for each input. Here S1 S0 = 00, so the switch points at D0 and Y copies D0.
Set S1 S0 to 10, which is 2 in binary. The switch swings to input D2, and Y changes from 0 to 1 because D2 holds a 1. None of the inputs changed; only the select bits did.
With the select held at 10, Y simply copies D2. When D2 flips, Y flips. D0 and D3 flip too, but nothing happens: the mux ignores every input it has not selected.
Reverse and real uses
A demultiplexer, or demux, does the reverse: one input, four outputs. Its select bits choose which output gets the input, and the others stay 0. Set to 10, it sends Y's 1 to output O2.
Put a mux and a demux at the two ends of one wire and give them the same select bits. Count the select through 00, 01, 10 and 11, and each input takes its turn on the shared wire to its matching output.
A CPU is full of muxes. To read register 2, the register number from the instruction drives the select bits, just like 10 here. Another mux chooses the ALU's second input: a register's value or a number written in the instruction.
The logic
;; step 1/10 · railway-switch ;; about: Select S, Path A, Path B, OR → Y 2-to-1 multiplexer inputs: A, B (the data) select: S (which one?) output: Y S = 0 → Y = A S = 1 → Y = B Like points on a railway: the trains (the bits) don't choose; the switch does.
In a real 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 carries a 1. The switch on the mux is a picture of the logic: the real circuit has no moving parts. In Python, 1 - s turns a bit 0/1 into 1/0 (NOT), & and | on 0 and 1 work as AND and OR, and d[2 * s1 + s0] uses the select bits as a list index.