简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM