简体   繁体   English

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

[英]How to convert 32-bit binary to float

I want to perform IEEE 754 conversion from 32-bit binary to float in python. 我想执行从32位二进制到python浮点的IEEE 754转换。

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: 您可以按以下方式使用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]

Giving you an output of: 提供以下输出:

21.5599994659
-21.5599994659

It all depends on how the integer is represented though. 这完全取决于整数的表示方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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