% This is part III of Lab Assignment 1
% Author - Jim Sochacki
% Converts a base 10 number to base 2
% There are two basic parts (a) The integer conversion from Part I
% (b) The decimal conversion.
base_10_num = input(' Give your base 10 number ');
%find the sign of the input
sign = 1;
if (base_10_num <0)
base_10_num = abs(base_10_num);
sign = -1;
end
base_10_int = floor(base_10_num); % integer part of input
base_10_dec = base_10_num - base_10_int; % fraction part of input
% part (a)
x = base_10_int;
i = 1; % counts the digit location a(i) is the ith digit
while (x > 1)
x = x/2;
xf = floor(x); % get integer part
if (x - xf == 0) % there should be no round off in the integer part
a(i) = 0;
else
a(i) = 1;
end
i = i + 1; % get the next digit
x = xf; % only need the integer part to continue algorithm
end
a(i) = 1; % in base two leading digit is always a 1
% a contains the base two digits of the integer. Now use Horner
n = i;
if (base_10_int <= 1)
poly = base_10_int;
else
poly = a(n-1) + a(n)*10; % 10 holds the digit place
for i = n-2:-1:1
poly = a(i)+ poly*10;
end
end
% poly contains the base 2 representation of the base 10 integer
int_part = poly;
% part (b)
x = base_10_dec;
% There are many decimals that cannot be converted like 0.42 we use a
% while loop with a break
a(1) = 0; % in decimal part the first digit is times 1/2.
i = 2; % counts the number of digits
while (x > 0) % This will only break for decimals that are finite base 2
x = x*2;
xf = floor(x);
if (xf == 0) % check if the number is greater than 1
a(i) = 0;
else
a(i) = 1;
x = x-1;
end
i = i+1;
if (i >= 52) % we showed in class that matlab has 52 digits in the
break % mantissa. get out of the while loop if we have checked
end % all digits in mantissa
end
n = i-1; % n is the number of fraction part digits calculated
% calculate the base 2 fraction part using Horner's method
poly = a(n-1) + a(n)*(1/10); % 1/10 holds the digit place
for i = n-2:-1:1
poly = a(i)+ poly*(1/10);
end
frac_part = poly;
num = int_part+frac_part;
strnum1 = sprintf(' The base 10 number %25.15f ', ...
sign*base_10_num);
strnum2 = sprintf(' in base 2 is %35.20f ',sign*num);
disp(strnum1)
disp(strnum2)