Can I teach you to do math in binary in 20 minutes?
Adding numbers in binary is a lot simpler than you might think. Follow along and
learn how it's done.
Note: I will mark all binary numbers in red, and regular decimal numbers
in blue.
Let's try an example
Imagine we want to calculate 3 +
1. In binary, they are
11, and 1 respectively.
1 1 <--- start
from the right
+ 0 1
------
We start from the right, by adding 1 +
1, which is 2 in
decimal. In binary, it's written as 10.
But when we are adding in binary, we can only add single digits,
0 or 1. So we need to
carry the 1, and add the
0.
1 <--- carry the one 1 1
+ 0 1
------ 0 <---
add the zero
Now we move on to the next number.
Carried from the previous 10's
↓ ↓ 1 1 1 1
+ 0 1
-------- 1 0 0
We calculate the carry with the next line, 1 +
1 + 0. But that also
gives 10, so we need to carry it again, and put
0 as the sum at the bottom.
And if we add the last 1 to the bottom, we have
100.
That's it. You've calculated 3 +
1 in binary. Try it yourself by hand with a
different number! At the bottom of this page there is a handy generator for
testing if you got it right. :)
The logic types
If you're interested in building the logic yourself in code, here's how to do
it. There are only 3 types needed.
XOR
Takes two inputs, A and B. If
they're different from each other, output is 1,
otherwise 0.
function OR(a, b) { if (a == 1 || b == 1) { return
1; } else { return
0; } }
These logic types can be implemented in hardware with the help of transistors
and resistors, but it's easier in code.
Here is the logic chart for adding numbers in binary:
Here, A and B are our two
numbers we want to add, and C is a carried number if the number is longer than
one digit. The Carry out leads into an identical chart, because you need to run
it on every digit in your two numbers, starting from the back.
Using the functions we defined earlier, XOR, AND, OR, and chaining them together
according to the chart, you can add numbers in binary. Test different numbers
for yourself below.