BINARY 32 BITS TO REAL CONVERTER

0

It turns out that I must convert the given binary with the following formulas, using point product for the summation.

I designed this code

import numpy as np

#Creamos el arreglo bs que me separa individualmente los elementos del string
bs=np.array(list('00111110001000000000000000000000'))

#el comando b.astype covierte los elemento de la lista a enteros
bs=bs.astype(int)

#Invertimos el arreglo así es más fácil implementar la fórmula
sb=bs[::-1]

#Tomamos ciertos segmentos del arreglo:
#s es el correspondiente al signo,
#e es el correspondiente al exponente,
#f es el correspondiente a la fracción.

s=sb[31:32]
f=sb[:23]
e=sb[23:31]

#Creamos la variable 'fe' que es la correspondiente a los primeros 8 términos del arreglo
#y así pues hallamos el producto punto tras hallar el término 2^i

fe=sb[:8]
ep = np.exp2(fe)

#'exp' es el resultado correspondiente a la sumatoria del exponente
exp=np.dot(e,np.exp2(fe))

#Creamos 'ff' puesto que el término de la sumatoria me decrece, lo que equivale a usar la cadena original
#Además es necesario crar otro arreglo que vaya desde i=1 hasta i=23 para eso creamos 'ff2'
#también creamos la variable 'efra' que es 1/'ff2' aplicándole exponencial puesto que así respetamos el signo
ff=f[::-1]
ff2=sb[1:24]
efra= 1./(np.exp2(ff2))

#'frac' es el producto punto que equivale a la sumatoria
frac=np.dot(ff,efra)

#Ahora pues, llamemos 'r' el real que buscamos y apliquemos la fórmula

r=((-1)**s)*(1+frac)*2**(exp-127)

print (r)

at the end the number gives me the order of e-37 and should give 0.15625

Thank you!

    
asked by Natalia Alvarez 28.02.2018 в 01:36
source

1 answer

1

The main error is in the conversion of bits to integers or doubles.

I have created a function that converts the inverted bits to their corresponding integer value, in the case of the exponent it can be used directly, but in the case of the mantissa the same can be used but multiplied by 2 ** - 23, obtaining the following:

import numpy as np

def list_to_int(l):
    return np.dot(l,np.exp2(np.arange(len(l))))

#Creamos el arreglo bs que me separa individualmente los elementos del string
bs=np.array(list('00111110001000000000000000000000'))

#el comando b.astype covierte los elemento de la lista a enteros
bs=bs.astype(int)
sb = bs[::-1]

s=sb[-1]
f=sb[:23]
e=sb[23:31]

exponent = list_to_int(e)
mantissa = list_to_int(f)*np.exp2(-len(f))
val = ((-1)**s)*(1+mantissa)*np.exp2(exponent-127)
print(val)

Output:

0.15625
    
answered by 28.02.2018 в 02:26