Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 55 ยท Real-World Projects

Project: A Binary Calculator

Build a working binary adder from logic gates, add subtraction with two's complement, and detect carry and overflow flags, then test it against every 8-bit input.

In this project you will build, from nothing but logic functions, the arithmetic unit of a tiny computer. You will start with gates, wire a full adder, chain eight of them into an adder, turn that same adder into a subtractor using two's complement, and finish with the flags a real CPU raises when a result is zero, negative, carried or overflowed. At the end you will prove it correct by checking it against all 65,536 pairs of 8-bit inputs.

Nothing here is new theory; it is the ideas of Boolean Logic and Logic Gates and Binary, Octal and Hexadecimal put to work. If either feels shaky, read it first. Real hardware is a bundle of wires; here the wires are JavaScript values of 0 and 1, so this is an honest model of the logic, not of the electronics.

The plan

The calculator has three layers, and each layer uses only the one below it.

flowchart TD
  G["Gates: AND, OR, XOR, NOT"] --> FA["Full adder (1 bit)"]
  FA --> RA["Ripple-carry adder (8 bits)"]
  RA --> ALU["ALU: add, subtract, flags"]
  ALU --> T["Exhaustive test against JavaScript maths"]

Each layer is built only from the layer above it in the picture.

To keep the code readable, we write bit lists with the least significant bit first, so bits[0] is the ones place and bits[7] is the top bit. Printing reverses them so we read them the usual way.

Step 1: gates, full adder and an 8-bit adder

A full adder takes bits a, b and a carry-in and produces a sum bit and a carry-out. The sum is a XOR b XOR carryIn. A carry leaves when both operands are 1, or when exactly one of them is 1 and a carry came in.

The adder below also records the carry that flows into the top bit (carryIntoTop). You will need it for the overflow flag in step 3.

JS Step 1: an 8-bit ripple-carry adder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two lines behave like ordinary arithmetic. In the third line 200 + 100 is 300, which needs nine bits, so the stored result is 300 - 256 = 44 and the carry-out is 1. The last line wraps from 255 to 0 the same way. The carry-out is the machine telling you the unsigned answer did not fit.

Step 2: subtraction with the same adder

A machine does not need a separate subtraction circuit. Recall two's complement: to negate a number, invert every bit and add 1. Then a - b is just a + (-b), which is

a + NOT(b) + 1

and the "+ 1" can come for free through the adder's carry-in. So subtraction costs one row of NOT gates and a single wire. Real CPUs do exactly this.

For subtraction the carry-out has a twist: it ends up 1 when no borrow was needed (when a >= b as unsigned numbers) and 0 when a borrow was needed. Many processors expose that as a "borrow" flag by inverting it, so be aware that conventions differ.

JS Step 2: subtract using add and invert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at 4 - 9. The adder produces 11111011, which is 251 as an unsigned number and -5 as a signed one. Both readings are the same bits; what they mean depends on how the program interprets them. The carry-out is 0 because unsigned 4 is smaller than unsigned 9, a borrow was needed.

Step 3: the ALU and its flags

An ALU (arithmetic logic unit) applies an operation and, alongside the result, raises small yes/no signals called flags. Programs and the CPU's branch instructions look at them to make decisions. We will produce four, which many real processors share:

Flag Name Set to 1 when
Z Zero all result bits are 0
N Negative the top bit of the result is 1
C Carry the adder produced a carry out of the top bit
V Overflow a signed result is wrong because it does not fit

Overflow needs care. Adding two positive numbers must give a positive result, and adding two negatives must give a negative one. If the result's sign breaks that rule, the signed answer is wrong. There is a neat hardware trick: overflow happens exactly when the carry into the top bit differs from the carry out of it, so V = carryIntoTop XOR carryOut. That is why the adder in step 1 recorded carryIntoTop.

JS Step 3: an ALU with Z, N, C and V flags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the lines slowly. 100 + 100 gives 11001000: as unsigned it is 200 and no carry, but as signed it is -56 and V is 1, because two positives produced a negative. 255 + 1 sets Z (the result is zero) and C (the carry left the top) but not V: as signed numbers, -1 + 1 = 0 is perfectly correct. The same bits can be an overflow for one interpretation and fine for the other, and the CPU gives you both flags so that the program can choose.

Step 4: prove it works

How do you know the circuit is right and not just right on your examples? With only 8 bits you can test everything. There are 256 ร— 256 = 65,536 input pairs, which the computer checks in a blink. We compare the sum with the real JavaScript sum wrapped to 8 bits, the difference with the real difference wrapped, and the overflow flag with a direct check on the signed range.

JS Step 4: exhaustive test of all 65,536 input pairs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If it prints the success line, your gate-built ALU agrees with ordinary arithmetic on every possible input. That kind of exhaustive check, or a mathematical proof, is how chip designers gain confidence, because a fault in silicon cannot be patched with an update.

Ideas to extend it

  • Widen the adder to 16 bits by changing WIDTH. The test now has over four billion pairs, so sample random pairs instead.
  • Add AND, OR, XOR and NOT as ALU operations, selecting between them with the op argument.
  • Add a shift-left, which doubles a number.
  • Build a multiplier from repeated shift-and-add, the way you multiply on paper.
  • Replace the ripple chain with a carry-lookahead idea: compute all carries at once for speed.

What is real and what is the stand-in? Full adders, the ripple chain, two's complement subtraction through carry-in, and the Z, N, C and V flags are how real ALUs work. The JavaScript operators &, | and ^ stand in for gates (each is a few transistors in hardware), the loop stands in for a row of wired adders that all exist at once, and real chips use faster carry designs. Flag names and the meaning of C for subtraction differ between processor families.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does the calculator compute a - b using only an adder?

    Inverting b and adding 1 produces -b in two's complement, so a + NOT(b) + 1 equals a - b.
  2. 2. The 8-bit adder returns 44 with carry-out 1 for 200 + 100. What does the carry-out tell you?

    300 needs nine bits; the stored value is 300 - 256 = 44 and the carry-out shows the lost ninth bit.
  3. 3. When is the signed overflow flag V set, according to the hardware rule used here?

    V = carry into the top bit XOR carry out of it. That detects a result whose sign disagrees with the operands.
  4. 4. 255 + 1 in 8 bits sets Z and C but not V. Why is V clear?

    The same bits mean 255 + 1 unsigned (carry) and -1 + 1 signed (correct). Overflow concerns the signed reading only.
  5. 5. Why can you test the 8-bit ALU on every possible input?

    Two 8-bit inputs have 65,536 combinations, so an exhaustive test finishes instantly. This is not possible for 64-bit inputs.

Summary

  • A full adder (two XORs, two ANDs and an OR) adds one bit with carry; eight in a row make a ripple-carry adder.
  • Subtraction reuses the adder: invert the second operand and set the carry-in to 1.
  • Flags report the outcome: Z for zero, N for negative, C for carry out, V for signed overflow.
  • Unsigned and signed readings of the same bits can differ, so the machine keeps separate flags for each.
  • Small designs can be tested exhaustively, which is how you build trust in a circuit.

Now give this arithmetic unit a controller that fetches instructions: Project: A Tiny CPU Simulator.