如何将 32 位二进制转换为浮点数

Sha*_*rma 0 python floating-point binary ieee-754

我想在 python 中执行从 32 位二进制到浮点数的 IEEE 754 转换。

我试过这个

import struct

f = int('11000001101011000111101011100001', 2)
print struct.unpack('f', struct.pack('i', f))[0]
Run Code Online (Sandbox Code Playgroud)

但这不适用于带有负符号位的数字。

预期的输出应该是这样的:

bintofloat(11000001101011000111101011100001)
>>> -21.56
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 5

你可以使用struct如下:

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]
Run Code Online (Sandbox Code Playgroud)

给你一个输出:

21.5599994659
-21.5599994659
Run Code Online (Sandbox Code Playgroud)

不过,这一切都取决于整数的表示方式。