Maths from switches
Adding two bits: 0+0=0, 0+1=1, 1+1=10 (sum 0, carry 1). The sum column is XOR, the carry is AND — a half adder. Chain them with carries and you can add numbers of any size.
From half to full to four bits
function halfAdder(a, b) {
return { sum: xor(a, b), carry: and(a, b) };
}
function fullAdder(a, b, carryIn) {
const first = halfAdder(a, b);
const second = halfAdder(first.sum, carryIn);
return { sum: second.sum, carry: or(first.carry, second.carry) };
}
function add4(a, b, carryIn = 0) {
let sum = 0;
let carry = carryIn;
for (let i = 0; i < 4; i++) {
const r = fullAdder((a >> i) & 1, (b >> i) & 1, carry);
sum |= r.sum << i;
carry = r.carry;
}
return { sum, carry };
}