Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

CS 101 – Binary Mathematics

In my last post, we discovered binary as a form of numeric representation. Like decimal, we can perform basic arithmetic operations with binary (and, consequently, hex).

Addition

We all know that 1 + 1 = 2, right? In binary, 1 + 1 = 10, as 10 is the binary representation of 2. By the same token, 10 + 11 = 101 (equivalent to 2 + 3 = 5). Big example:

  1 0 1 0 1 1 1 1

+ 1 0 1 0 1 0 0 1

—————————–

1 0 1 0 1 1 0 0 0

Double Check: 95 + 89 = 184

Binary addition is surprisingly simple.

Subtraction

Negative numbers are a bit tricky in binary. The best method of representing them is the two’s complement method, in which we invert every bit, then add 1. Thus, the negative form of 1 0 1 0 1 0 0 1 is (0 1 0 1 0 1 1 0    +    1), or 0 1 0 1 0 1 1 1. We then treat subtraction as addition, using the negative form in place of the subtrahend:

1 0 1 0 1 1 1 1 – 1 0 1 0 1 0 0 1

= 1 0 1 0 1 1 1 1 + 0 1 0 1 0 1 1 1

=0 0 0 0 0 1 1 0

Double Check: 95 – 89 = 6

Note: If there is a carry-over result, we have to “throw it away”. This is possible, and must be remembered.

Multiplication

Multiplication of binary numbers is actually very similar to multiplication of decimal. Ultimately, it is a “multiply and shift” function. This is best explained by example:

0 1 0 1 * 1 1 0 1

= 0101 * 1 + 0101 * 0 + 0101 * 100 + 0101*1000

= 0101 + 010100 + 0101000

=1000001

Double check: 5 * 13 = 65

Division

This…is a harder topic. If we want to use floating-point results, we have to cover another substantial topic first…

Integer division is fairly easy, so long as we throw away any remainders. This is the same as decimal division, using continual shifts and subtraction.

As with multiplication, this is best described by example:

1000001 / 1101

= 00001xx          1000001 – 0110100 = 1101

= 0000101          1101 – 1101 = 0

= 0101

Double check: 65 / 13 = 5

Modulo

Most people haven’t heard of the “modulo” operation. Put simply, the modulo operation finds the remainder we throw away during division. In decimal, we could perform the operation 16 % 5 = 1. That is, the remainder of the operation 16 / 5 is 1. We do the same basic thing in binary: we perform binary division, then look at the remainder.

In the above division example, we find that 1000001 % 1101 = 0, because we have no remainder.

Homework

Perform all five operations on the following number combinations: {0101, 1101} {00110101, 00110101} {0101, 1101, 0001, 1000}   You won’t have to do this math by hand (ever?), but you should practice enough to understand what’s going on.

For further explanations and exercises, feel free to visit Binary Math.