Boolean Logic in Circuits and Code
Every computation a CPU performs is built from logic gates: AND, OR and NOT wired together. The propositional logic of this course is exactly the mathematics of these circuits. This lesson builds an adder from gates, shows that a few gate types are enough for everything, and applies the same algebra to clean up conditions in code.
Gates are connectives
| Gate | Formula | Python on bits |
|---|---|---|
| NOT | 1 - a, a ^ 1 |
|
| AND | a & b |
|
| OR | a | b |
|
| XOR | a ^ b |
|
| NAND | 1 - (a & b) |
Functional completeness
Any Boolean function can be written with AND, OR and NOT: read off its DNF from the truth table, one AND-term per true row. In fact NAND alone is enough:
This is why chip manufacturing can be built around a single kind of cell.
from itertools import product
nand = lambda a, b: 1 - (a & b)
NOT = lambda a: nand(a, a)
AND = lambda a, b: NOT(nand(a, b))
OR = lambda a, b: nand(NOT(a), NOT(b))
XOR = lambda a, b: AND(OR(a, b), nand(a, b))
ok = all(NOT(a) == 1 - a and AND(a, b) == a & b and OR(a, b) == a | b and XOR(a, b) == a ^ b
for a, b in product([0, 1], repeat=2))
print("NOT, AND, OR, XOR built from NAND only:", ok)NOT, AND, OR, XOR built from NAND only: True
Building an adder
Adding two bits gives a sum bit and a carry: , (a half adder). A full adder also takes an incoming carry :
Chaining full adders, each carry feeding the next, gives a ripple-carry adder for -bit numbers. The carry out of the top bit is lost in fixed-width arithmetic, which is why 8-bit addition is arithmetic modulo .
def full_adder(a, b, cin):
s = a ^ b ^ cin
cout = (a & b) | (cin & (a ^ b))
return s, cout
def ripple_add(x, y, bits=8):
carry, result = 0, 0
for i in range(bits):
s, carry = full_adder(x >> i & 1, y >> i & 1, carry)
result |= s << i
return result, carry
for x, y in [(23, 42), (200, 100), (255, 1)]:
r, c = ripple_add(x, y)
print(f"{x} + {y} = {r} (carry out {c}) true sum mod 256: {(x + y) % 256}")
# exhaustive check over all 8-bit pairs
print(all(ripple_add(x, y)[0] == (x + y) % 256 for x in range(256) for y in range(256)))23 + 42 = 65 (carry out 0) true sum mod 256: 65
200 + 100 = 44 (carry out 1) true sum mod 256: 44
255 + 1 = 0 (carry out 1) true sum mod 256: 0
True
The ripple adder is slow for wide words because each carry waits for the previous one. Carry-lookahead adders compute carries in parallel with more gates: a trade-off between circuit size and depth, which are the two complexity measures of circuits.
Logic in everyday code
The same laws simplify conditions. Using De Morgan, distributivity and absorption:
from itertools import product
def before(user_ok, admin, banned, owner):
return not (not user_ok or banned) and (admin or owner) or (admin and user_ok and not banned)
def after(user_ok, admin, banned, owner):
return user_ok and not banned and (admin or owner)
print("equivalent:", all(before(*v) == after(*v) for v in product([False, True], repeat=4)))equivalent: True
The first condition simplifies: , and by absorption, because the second term is already contained in the first. Checking all inputs proves the refactoring is safe.
In software
Hardware description languages (Verilog, VHDL) describe circuits as Boolean formulas that synthesis tools minimise with exactly these laws (Karnaugh maps, Quine–McCluskey, modern SAT-based tools). Bit manipulation tricks (x & (x - 1) clears the lowest set bit, x & -x isolates it) are Boolean algebra on machine words, used in bitsets, chess engines and compression code.
Exercises
Exercise 1: Half adder table
Write the truth table of the half adder (inputs ; outputs ).
Answer
, , , .
Solution
is 1 when exactly one input is 1; is 1 only for .
Exercise 2: NOR is complete too
Express NOT and OR using only NOR, where .
Answer
; .
Solution
. Negating NOR gives OR. With NOT and OR, AND follows by De Morgan: .
Exercise 3: Lowest set bit (code)
Show that x & (x - 1) clears the lowest 1-bit of x, and use it to count 1-bits.
Answer
Subtracting 1 flips the lowest 1 and all 0s below it; AND keeps the higher bits.
Solution
Each iteration removes one 1-bit, so the loop runs once per set bit (Kernighan's method).
def popcount(x):
count = 0
while x:
x &= x - 1
count += 1
return count
for x in [0b101100, 255, 1 << 40, 12345]:
print(bin(x), bin(x & (x - 1)), popcount(x), bin(x).count("1"))0b101100 0b101000 3 3
0b11111111 0b11111110 8 8
0b10000000000000000000000000000000000000000 0b0 1 1
0b11000000111001 0b11000000111000 6 6
Test yourself
Which single gate type can build every Boolean function?
- AND
- OR
- XOR
- NAND
In a full adder, the sum bit is…
Why is 8-bit addition arithmetic modulo 256?
- Because of rounding
- The carry out of the top bit is discarded
- Because 256 is prime
- It is not