Floating point/Lesson Two

Introduction to Binary
Computers have to store numbers as either a '0' or a '1.' Thus, binary digits must be used, where a number is represented as a string of zeros and ones.

In the decimal (10-based) system, a number is written as we normally write it. The placement of the number indicates how many of each power of ten the number has. For instance,

572001.5 = 5 × 10-1 + 1 × 100 + 0 × 101 + 0 × 102 + 2 × 103 + 7 × 104 + 5 × 105

The number ½ is written as 0.5 = 5 × 10-1.

Instead of using '10' as the above indicates we do in decimal, we use a '2' in binary. Thus, 0.5 = 1 × 2-1 = 0.1 (base 2).

Conversion into binary
To convert a number into binary, consider it's decimal and it's whole parts.

Let's say we have to convert the number 452.5505 into binary. The first part is the whole number. We need to divide the number by 2, and then note the remainder. Repeat the process.

452 ÷ 2 = 226 R 0

226 ÷ 2 = 113 R 0

113 ÷ 2 = 56 R 1

56 ÷ 2 = 28 R 0

28 ÷ 2 = 14 R 0

14 ÷ 2 = 7 R 0

7 ÷ 2 = 3 R 1

3 ÷ 2 = 1 R 1

1 ÷ 2 = 0 R 1

Thus, the remainders are 0, 0, 1, 0, 0, 0, 1, 1, and 1. Go backwards; the result is 111000100.

This works because by dividing by 2, we are determining the number of places. The remainder tells us if we need to add an additional number to that binary spot.

For the decimal, we do the opposite. We multiply by 2, and we record the non-decimal.

.5505 × 2 = 1.101 (1)

.101 × 2 = .202 (0)

.202 × 2 = .404 (0)

.404 × 2 = .808 (0)

.808 × 2 = 1.616 (1) ... and so on.

The number is then 1111000100.10001..., base 2.

Conversion out of Binary
To convert out of binary, simply use the definition.

110.01 = 1 × 2-2 + 0 × 2-1 + 0 × 20 + 1 × 21 + 1 × 22

110.01 = 6.25

Problems with conversion into binary
When numbers are converted into binary, sometimes, an otherwise easy-to-notate number becomes burdensome to store. An example is 0.1.

0.1 × 2 = 0

0.2 × 2 = 0.4

0.4 × 2 = 0.8

0.8 × 2 = 1.6

0.6 × 2 = 1.2

0.2 (repeats)

0.1 (base 10) thus repeats as 0.0001100110011...

This can cause a problem if the user is not aware of the issue. If a number has a finite representation in decimal, it does not necessarily have this in binary.

Matlab Code
In Matlab, there is code which will convert integers from binary to decimal and vice versa. The command is dec2bin and bin2dec. The bin2dec command must be entered as a string, so single quotes must be put around the number. Below is an example of the command.

>> dec2bin(452)

ans =

111000100

>> bin2dec('111000100')

ans =

452

Homework
1. Convert the following decimal numbers into binary: 46, 578.2, 205.4.

2. Convert the following binary numbers into decimal: 1001.1, 10, 111.01

Source
Cheney Ward and David Kincaid. Numerical Methods and Computing. Belmont, CA: Thomson, 2004.