Sikau

How computers work · Day 7 · about 40 min

Adding with gates

Half adders, full adders and a 4-bit ripple-carry adder.

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 };
}

The rest of this lesson

  • Tracing a 4-bit additionexplain
  • Faster than rippleexplain
  • Overflowpredict
  • Complete the half adderfill
  • Build the adderwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work