digiwleeaTools
LearnGlossaryAboutCheat sheetHow a CPU worksToolsOpen the lab →

How to build a XOR gate from NAND gates from logic gates

An XOR gate can be built from exactly four NAND gates: one shared NAND feeds two middle NANDs, and a final NAND merges them into A XOR B.

NAND is a universal gate: any logic function can be built from NANDs alone. XOR is the classic exercise, and the four-gate construction below is the minimal one. It is also how XOR is often realized on chips that standardize on NAND.

Live circuit: click the inputs to toggle them and watch the outputs update. It runs the real simulator, right here on the page.

Open this circuit in the lab →

What you need

Step by step

  1. Place two inputs, A and B.
  2. Wire both into a first NAND gate. Call its output N1: it is 0 only when A and B are both 1.
  3. Wire A and N1 into a second NAND, and B and N1 into a third. Each middle gate goes low only when its input is 1 while the other input is not also 1.
  4. Wire the two middle outputs into a fourth NAND. Its output Y is high exactly when A and B differ: that is XOR.
  5. Probe Y and sweep the four input combinations to confirm the XOR truth table.

XOR from NAND truth table

ABY
000
011
101
110

The output is 1 exactly when the inputs differ. Follow the middle gates on the live circuit above to see why: the shared first NAND ensures the 1,1 case is excluded from both middle paths.

You can also read the full theory in the lesson on the NAND gate. Prefer to build it yourself from scratch? Open the digiwleea lab and place the gates on the canvas, or start from the logic gate simulator.

Build more parts from gates

Each of these is one step from a transistor to a working CPU. Build every gate from CMOS transistors and work all the way up in the free digiwleea lab and course.

Open the XOR gate from NAND gates in the lab →

Frequently asked

How many NAND gates does an XOR gate need?

Four. One NAND shared by both inputs, two middle NANDs that each combine one input with the shared output, and one final NAND that merges the middle pair. Four is the minimum with two-input NANDs.

Why is NAND called a universal gate?

Because every Boolean function can be built from NAND gates alone: NOT is a NAND with its inputs tied together, AND is NAND followed by NOT, and OR is NAND fed by two NOTs. XOR from four NANDs is the classic demonstration.

Can XOR be built from NOR gates instead?

Yes, NOR is also universal. The symmetric construction takes five NOR gates (or four plus an inverter depending on the variant), one more than the NAND version, which is part of why NAND is usually preferred.