Write code to account for a repeating segment when convertin
Write code to account for a repeating segment when converting from decimal to binary. Test your code on 0.68 and 0.4.
Solution
Executable code:
%input as decimal
decimalInput=0.68;
a=0;
b=1;
%loop to VALID input
while a == 0
if decimalInput/2 > 0
if decimalInput/2 ~= round(decimalInput/2)
bin(b) = 1;
end
if decimalInput/2 == round(decimalInput/2)
bin(b) = 0;
end
end
%dividing input by 2
if decimalInput/2 < 1
bin(b) = 1;
a = 1;
else
b=b+1;
decimalInput = floor(decimalInput/2);
end
end
%computing the lenght
newbinVal=zeros(1,length(bin));
%loop to as long as the length
for a = 1:length(bin)
%
newbinVal(a) = bin((length(bin)-a)+1);
end
if length(bin) < 8
bin = [zeros(1,8-length(bin)), newbinVal];
else
bin = newbinVal;
end
fprintf(\'Repeating segments %i\ \', bin)


