Search code examples
pythonbinaryfloating-pointieee-754

How to convert 32-bit binary to float


I want to perform IEEE 754 conversion from 32-bit binary to float in python.

i have tried this

import struct

f = int('11000001101011000111101011100001', 2)
print struct.unpack('f', struct.pack('i', f))[0]

but this doesn't work for numbers with negative sign bit.

Expected output should be like this:

bintofloat(11000001101011000111101011100001)
>>> -21.56

Solution

  • You could use struct as follows:

    import struct
    
    f = int('01000001101011000111101011100001', 2)
    print struct.unpack('f', struct.pack('I', f))[0]
    
    f = int('11000001101011000111101011100001', 2)
    print struct.unpack('f', struct.pack('I', f))[0]
    

    Giving you an output of:

    21.5599994659
    -21.5599994659
    

    It all depends on how the integer is represented though.