0

I would to convert a float to binary repr. then convert back the binary repr. to float in python.

For the first part float to binary, I am using Float to binary @Ozbolt answer,

def float_to_bin(x):
  if x == 0:
    return "0" * 64
  w, sign = (float.hex(x), 0) if x > 0 else (float.hex(x)[1:], 1)
  mantissa, exp = int(w[4:17], 16), int(w[18:])
  return "{}{:011b}{:052b}".format(sign, exp + 1023, mantissa)

Which work very good, for example calling :

float_to_bin(10.24)

answer:

0100000000100100011110101110000101000111101011100001010001111011

But how to reverse the process (to do binary to float)? I expect something like:

bin_to_float("0100000000100100011110101110000101000111101011100001010001111011")

which answer:

10.24
A. STEFANI
  • 6,707
  • 1
  • 23
  • 48

0 Answers0