如何将32位二进制转换为浮点数 [英] How to convert 32-bit binary to float
本文介绍了如何将32位二进制转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想执行从32位二进制到python浮点数的IEEE 754转换.
I want to perform IEEE 754 conversion from 32-bit binary to float in python.
我已经尝试过了
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
推荐答案
您可以按以下方式使用struct
:
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]
为您提供以下输出:
21.5599994659
-21.5599994659
这完全取决于整数的表示方式.
It all depends on how the integer is represented though.
这篇关于如何将32位二进制转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文