How to convert 32-bit binary to float

回眸只為那壹抹淺笑 提交于 2019-12-10 12:13:56

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/33483846/how-to-convert-32-bit-binary-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!