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.
- 4NAND gates
- Yesfewest possible
- 2inputs
- 1output
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
- N = NAND(A, B). 0 only when both inputs are 1.
- NAND(A, N). 0 only when A is 1 and B is 0.
- NAND(N, B). 0 only when B is 1 and A is 0.
- NANDs the two middle results. 1 when either one fired, so 1 exactly when A and B differ.
Truth table
| A | B | Q |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
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.