Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

The function has this signature: def float_string_to_binary(float_string) It takes a decimal number string representing a floating point value and prints out the binary decimal string will fit within this format. The format t using the floating point format described below. You may assume that all values of the class. It is a 16-bit format (not quite the same as the IEEE 16-bit format) Sign: the first bit (most significant bit: bit 15). 1 means negative, 0 means positive Exponent: four bits for the exponent (bits 14-11). The exponent has a bias of 7.

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)