TExcelTAD
Home › Discrete Mathematics › Boolean Logic in Circuits and Code

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 ¬a\neg a 1 - a, a ^ 1
AND a∧ba \land b a & b
OR a∨ba \lor b a | b
XOR a⊕ba \oplus b a ^ b
NAND ¬(a∧b)\neg(a \land b) 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:

¬a=NAND(a,a),a∧b=¬ NAND(a,b),a∨b=NAND(¬a,¬b)\neg a = \text{NAND}(a, a), \qquad a \land b = \neg\,\text{NAND}(a, b), \qquad a \lor b = \text{NAND}(\neg a, \neg b)

This is why chip manufacturing can be built around a single kind of cell.

python · try it yourself
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: s=a⊕bs = a \oplus b, c=a∧bc = a \land b (a half adder). A full adder also takes an incoming carry cinc_{in}:

s=a⊕b⊕cin,cout=(a∧b)∨(cin∧(a⊕b))s = a \oplus b \oplus c_{in}, \qquad c_{out} = (a \land b) \lor (c_{in} \land (a \oplus b))

Chaining nn full adders, each carry feeding the next, gives a ripple-carry adder for nn-bit numbers. The carry out of the top bit is lost in fixed-width arithmetic, which is why 8-bit addition is arithmetic modulo 282^8.

python · try it yourself
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:

python · try it yourself
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: ¬(¬u∨b)=u∧¬b\neg(\neg u \lor b) = u \land \neg b, and (u∧¬b∧(a∨o))∨(a∧u∧¬b)=u∧¬b∧(a∨o)(u \land \neg b \land (a \lor o)) \lor (a \land u \land \neg b) = u \land \neg b \land (a \lor o) by absorption, because the second term is already contained in the first. Checking all 242^4 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 a,ba, b; outputs s,cs, c).

Answer

(0,0)→(0,0)(0,0) \to (0,0), (0,1)→(1,0)(0,1) \to (1,0), (1,0)→(1,0)(1,0) \to (1,0), (1,1)→(0,1)(1,1) \to (0,1).

Solution

s=a⊕bs = a \oplus b is 1 when exactly one input is 1; c=a∧bc = a \land b is 1 only for 1+1=1021 + 1 = 10_2.

Exercise 2: NOR is complete too

Express NOT and OR using only NOR, where NOR(a,b)=¬(a∨b)\text{NOR}(a, b) = \neg(a \lor b).

Answer

¬a=NOR(a,a)\neg a = \text{NOR}(a, a); a∨b=¬ NOR(a,b)=NOR(NOR(a,b),NOR(a,b))a \lor b = \neg\,\text{NOR}(a, b) = \text{NOR}(\text{NOR}(a, b), \text{NOR}(a, b)).

Solution

NOR(a,a)=¬(a∨a)=¬a\text{NOR}(a, a) = \neg(a \lor a) = \neg a. Negating NOR gives OR. With NOT and OR, AND follows by De Morgan: a∧b=¬(¬a∨¬b)a \land b = \neg(\neg a \lor \neg b).

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).

python · try it yourself
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?

  1. AND
  2. OR
  3. XOR
  4. NAND

In a full adder, the sum bit is…

  1. a∧b∧cina \land b \land c_{in}
  2. a⊕b⊕cina \oplus b \oplus c_{in}
  3. a∨b∨cina \lor b \lor c_{in}
  4. ¬(a⊕b)\neg(a \oplus b)

Why is 8-bit addition arithmetic modulo 256?

  1. Because of rounding
  2. The carry out of the top bit is discarded
  3. Because 256 is prime
  4. It is not