TEST: test_values = \'0 0.000 127 -100.5\'.split() for value in test_values: pri
ID: 3732471 • Letter: T
Question
TEST:
test_values = '0 0.000 127 -100.5'.split()
for value in test_values:
print(value)
float_string_to_binary(value)
print()
RESULT:
0
0 0000 00000000000
0.000
0 0000 00000000000
127
0 1101 11111100000
-100.5
1 1101 10010010000
1.2
0 0111 00110011010
511.875
0 1111 11111111111
Explanation / Answer
ANSWER:
def float_string_to_binary(float_string):
f=float(float_string) #store float_string as a float value
n=abs(int(f)); #stores the non-decimal part without sign (eg. when f=-100.5, n=100)
exp_int=0;
for i in range(1,9): #find exponent by finding the greatest power of 2 less than n, then add 7
if(pow(2,i)>n):
exp_int=i-1;
break;
if exp_int!=0: exp_int+=7
m1="" #binary value of non decimal part
m2="" #binary value of decimal part
ex="" #binary value of exponent
for i in range(0,4): #convert exponent to binary (Note: the for loop produces the answer in reverse)
ex=ex+str(exp_int%2);
exp_int=int(exp_int/2);
ex=ex[::-1] #reverses the output of the for loop
for i in range(0,8): #similarly for m1
m1=m1+str(n%2);
n=int(n/2);
if(n==0):break;
d=abs(f-int(f)); #stores decimal part of f
for i in range(0,11): #convert to binary(Note: This loop produces the answer in order i.e not reversed)
m2=m2+str(int(d*2))
d=d*2-int(d*2);
mantissa=(m1[::-1]+m2)[1:12] #concatenate m1 and m2, and take the required 11 bits, excluding the first 1
if(f<0):
print(1,ex,mantissa)
else:
print(0,ex,mantissa)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.