Binary arithmetic

From CPUdev wiki
Jump to navigation Jump to search

As the name digital implies, digital computers work on on bits with a value of either 0 or 1. Accordingly, all operations, including arithmetic, operate on 0 or 1 values.

Numbers that consists only of 0 or 1s are called binary or base2 numbers. Binary numbers are often suffixed with a subscript 2, for example 10110112.

Converting between decimal and binary

Decimal as a sum of powers of 10

Any decimal number can be written as a sum of power of 10s. For example:

  • 42 = 4*101 + 4*100
  • 57005 = 5*104 + 7*103 + 0*102 + 0*101 + 5*100
  • 48.879 = 4*101 + 8*100 + 8*10-1 + 7*10-2 + 9*10-3

Binary numbers can be written in the same way though with powers of 2 instead of 10.

Converting from binary to decimal

  • 10102 = 1*23 + 0*22 + 1*21 + 0*20 = 8 + 2 = 10
  • 100.012 = 22 + 2-2 = 4 + 1/4 = 4.25

Converting from decimal to binary

  1. Divide the decimal number by 2.
  2. Append the remainder to the left of the binary number.
  3. Repeat with quotient as dividend until it is 0.

For example:

  • 29 = 111012
    • 29 / 2 = 14, remainder 1
    • 14 / 2 = 7, remainder 0
    • 7 / 2 = 3, remainder 1
    • 3 / 2 = 1, remainder 1
    • 1 / 2 = 0, remainder 1

The same technique can be used for rational numbers.

  1. First multiply by some power of 2 to convert it to an integer.
  2. Apply above procedure.
  3. Divide by the same power of 2 to get the correct result.

Mathematical operations

The same techniques used for addition, multiplication ... used for decimal numbers can also be used for binary numbers.

Addition & subtraction

  22       101102
+ 19     + 100112
----     --------
  41      1010012

Multiplication

  12         11002
*  5       *  1012
----       -------
  10         11002
+ 50            02
----     + 1100002
  60     ---------
            1111002

Division

  372 | 5        101110100 | 1012
- 35  +----    - 101       +---------
----  | 74     -----       | 10010102
   22 |            01      |
 - 20 |         -   0      |
 ---- |         -----      |
    2 |             11     |
                 -   0     |
                 -----     |
                    110    |
                  - 101    |
                  -----    |
                      11   |
                   -   0   |
                   -----   |
                      110  |
                    - 101  |
                    -----  |
                        10 |
                     -   0 |
                     ----- |
                        10 |