Classic Happy Relax Passionate Dreamless Halloween Photoshop Netscape DOS

Howto » Miscellaneous » Binaries and Decimals

Binary to decimal

It is easy to transform a binary number into a decimal number. Just compute the powers of two that correspond to ones in the binary number. For example:

1101 binary = 1 · 23 + 1 · 22 + 0 · 21 + 1 · 20 = 8 + 4 + 1 = 13

Fractional binary numbers use negative powers of two. For example:

1.101 binary = 1 · 20 + 1 · 2-1 + 0 · 2-2 + 1 · 2-3 = 1 + 0.5 + 0.125 = 1.625



Decimal to binary

Converting decimal numbers to binary numbers is a little trickier. Here is an algorithm that converts a decimal integer into its binary equivalent. Keep dividing the integer by 2, keeping track of the remainders. Stop when the number is 0. Then write the remainders as a binary number, starting with the last one. For example:

100 / 2 = 50 R 0
50 / 2 = 25 R 0
25 / 2 = 12 R 1
12 / 2 = 6 R 0
6 / 2 = 3 R 0
3 / 2 = 1 R 1
1 / 2 = 0 R 1

Therefore, 100 in decimal is 1100100 in binary.

Conversely, to convert a fractional number < 1 to its binary format, keep multiplying by 2. If the result is > 1, substract 1. Stop when the number is 0. Then use the digits before the decimal point as the binary digits of the fractional part, starting with the first one. For example:

0.35 · 2 = 0.7
0.1 · 2 = 1.4
0.4 · 2 = 0.8
0.8 · 2 = 1.6
0.6 · 2 = 1.2
0.2 · 2 = 0.4

Here the pattern repeats.
That is, the binary representation of 0.35 is 0.01 0110 0110 0110 . . .