NAND Bricks

How to build an XOR gate from NAND gates

An XOR gate takes four NAND gates. The first NANDs A and B together. The second NANDs A with that result, the third NANDs B with it, and the fourth NANDs those two. The output is 1 when exactly one of A and B is 1.

Inputs
1NAND2NAND3NAND4NANDA1B01Q
Click the inputs to try every combination. Green wires carry 1 and red wires carry 0. The small numbers match the steps below.
Open this circuit in NAND BricksLoads it as a new board with its truth table, ready to run.

The formula

Q = NAND(NAND(A, N), NAND(B, N)), where N = NAND(A, B)

How it works

XOR, "exclusive or", is 1 when A and B are different. It is the classic NAND puzzle, because the obvious build uses five gates and the neat one uses four.

Start with N = NAND(A, B). N is 1 unless both inputs are 1, so A AND N is 1 exactly when A is 1 and B is 0. The second gate computes NAND(A, N), which is 0 in exactly that case. The third gate does the same for B, and is 0 exactly when B is 1 and A is 0.

The last gate outputs 1 if either of those two is 0, meaning "A is on and B is off" or "B is on and A is off". That is XOR.

The trick is that the first gate is shared. Both middle gates use it, which saves a gate over the textbook formula (A AND NOT B) OR (B AND NOT A).

Gate by gate

  1. N = NAND(A, B). 0 only when both inputs are 1.
  2. NAND(A, N). 0 only when A is 1 and B is 0.
  3. NAND(N, B). 0 only when B is 1 and A is 0.
  4. NANDs the two middle results. 1 when either one fired, so 1 exactly when A and B differ.

Truth table

ABQ
000
011
101
110

Why 4 NAND gates?

Four is the fewest possible. We ran an exhaustive search over every circuit of three NAND gates or fewer, and none of them make XOR.

Where it's used

XOR is the sum bit of binary addition, the core of parity checks and checksums, and a quick "are these two bits different?" test. The half adder in the next guides is an XOR plus one more gate.