
In pseudo code the same algorithm can be documented as:
x = number_to_be_converted;
k = number_digits - 1;
/* number_digits = 8 so that while-loop starts at 7 */
while (k >= 0) do
begin
if (x-2^k) < 0 then d(k) = 0
else
begin
d(k) = 1;
x = x-2^k;
end
k = k-1;
end;
trace loop:
setup:
x=217
k=7
looping:
k=7 k=3
217-2^7=89 9-2^3=1
d(7)=1 d(3)=1
x=89 x=1
k=6 k=2
89-2^6=25 1-2^2=-3
d(6)=1 d(2)=0
x=25
k=5 k=1
25-2^5=-7 1-2^1=-2
d(5)=0 d(1)=0
k=4 k=0
25-2^4=9 1-2^0=0
d(4)=1 d(0)=1
x=9 x=0
In pseudo code the same algorithm can be documented as:
N = number_to_be_converted;
x = quotient;
M = current_digit;
if (N >= 0) then
begin
x = N;
k = 0;
while (k < 8) do
begin
d(k) = mod(x,2)
x = int(x/2)
k = k+1
end
end;
trace loop:
setup:
x=217
k=0
looping:
k=1
d(0) = mod(217,2) = 1
x=int(217,2) = 108 odd
k=2
d(1) = mod(108,2) = 0
x=int(108,2) = 54 even
k=3
d(1) = mod(54,2) = 0
x=int(54,2) = 27 even
k=4
d(1) = mod(27,2) = 1
x=int(27,2) = 13 odd
k=5
d(1) = mod(13,2) = 1
x=int(13,2) = 6 odd
k=6
d(1) = mod(6,2) = 0
x=int(6,2) = 3 even
k=7
d(1) = mod(3,2) = 1
x=int(3,2) = 1 odd
k=8
d(1) = mod(1,2) = 1
x=int(1,2) = 0 odd
How about fractions?
No one said we couldn't have negative powers of two!
Binary to decimal - conversion is always exact
Decimal to binary - conversions are not always exact
Next Section: Chapter 3 - Number Systems
Previous Section: Chapter 1 - Course Introduction
EEAP 282 Class Notes Table of Contents