You already know how to add numbers on paper: stack them up, add the right-hand column first, and
carry a digit to the next column whenever a total gets too big to fit. Adding
binary numbers works in exactly the same way — line the bits up, add from
the right, and carry. The only difference is how soon you have to carry. In ordinary
(denary) numbers a column can hold up to
This matters because addition is the one operation a computer's processor does more than any other. Multiplication is just repeated addition, subtraction is addition of a negative, and even drawing graphics or running a game boils down to a chip called the ALU adding binary numbers billions of times a second. Learn these four little rules and you know how a computer does sums.
Because each bit is only
Notice the pattern: you write down the ones part of the total and carry the twos part — precisely what you do in denary, where you write the units and carry the tens. Binary is not a new skill, just the same skill with an earlier carry.
Let's add
Reading the bottom row:
This program adds two binary numbers the way you would on paper: it walks both strings from the
right, applies the four rules with a running carry, and builds the answer digit by
digit. At the end it double-checks the result by converting everything to ordinary numbers with
parseInt. Change the two a and b strings and press
Run.
The loop keeps going while there are bits left in either number or a carry still needs writing — that last condition is what lets the answer grow an extra digit when two big numbers overflow their width.
On paper the answer can always grow one more column on the left. Inside a computer it often
can't: numbers are stored in a fixed number of bits — commonly
Add the two
Processors keep a special carry flag that switches on exactly when this happens, so a program can notice and react. But if nobody checks it, overflow is silent — and it is behind real bugs, from the arcade game Pac-Man's unplayable level 256 to aircraft that had to be rebooted before a counter overflowed. When you fix a number's width, always ask whether the biggest possible answer still fits.
Happily, no. Computers almost never build separate subtracting circuitry. Instead they store
negative numbers in a clever form called two's complement, which turns