NAND and NOR: the universal gates

A NAND gate is universal: NOT, AND, OR, and therefore any circuit at all, can be built from NAND gates only. The same is true of NOR. In CMOS chips a NAND gate needs just four transistors, fewer than AND (which is a NAND followed by a NOT), so real circuits are often mostly NAND and NOR.

Everything from NAND

GateBuilt from NANDGates
NOT AA NAND A1
A AND B(A NAND B) NAND (A NAND B)2
A OR B(A NAND A) NAND (B NAND B)3
A XOR Bfour NANDs (see below)4

Why does the OR work? (A NAND A) is A', so the result is (A' · B')' which by De Morgan is A + B.

def nand(a, b):
    return 1 - (a & b)

def not_(a):
    return nand(a, a)

def and_(a, b):
    return not_(nand(a, b))

def or_(a, b):
    return nand(not_(a), not_(b))

def xor_(a, b):
    m = nand(a, b)
    return nand(nand(a, m), nand(b, m))

for a in [0, 1]:
    for b in [0, 1]:
        ok = (and_(a, b), or_(a, b), xor_(a, b)) == (a & b, a | b, a ^ b)
        print(a, b, "AND", and_(a, b), "OR", or_(a, b), "XOR", xor_(a, b), "correct:", ok)
Open in compiler

Converting a circuit

A sum of products (an OR of ANDs) becomes NAND–NAND directly: replace every AND gate and the final OR gate with NAND gates. By De Morgan, ((AB)'(CD)')' = AB + CD. In the same way, a product of sums becomes NOR–NOR.

def nand(a, b):
    return 1 - (a & b)

# F = AB + CD, built from three NAND gates
wrong = 0
for row in range(16):
    a, b, c, d = (row >> 3) & 1, (row >> 2) & 1, (row >> 1) & 1, row & 1
    if nand(nand(a, b), nand(c, d)) != (a & b) | (c & d):
        wrong += 1
print("rows where NAND-NAND differs from AB + CD:", wrong)
Open in compiler

Early chips such as the famous 7400 contained four NAND gates each, and whole computers, including the Apollo Guidance Computer that flew to the Moon, were built from NOR gates alone.

Common mistakes

  • Thinking NAND then NOT is the same as NAND twice: NOT needs one NAND with both inputs joined.
  • Mixing up the conversions: SOP → NAND–NAND, POS → NOR–NOR.
  • Assuming AND is "simpler" than NAND in hardware. In CMOS it is the other way round.

Quick check

1. How do you make NOT A from a NAND gate?
2. How many NAND gates make an OR gate?
3. An OR of ANDs (SOP) is turned into:
4. Why are NAND gates common in chips?
My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.