浮动到二进制< - >二进制到浮点转换

时间:2014-02-06 16:16:56

标签: python floating-point

我想将一个浮点数转换为二进制字符串并返回。

我试过了:

import struct
from ast import literal_eval


float_to_binary = bin(struct.unpack('!i',struct.pack('!f', 3.14))[0])
print (float_to_binary)

binary_to_float = float(int(float_to_binary, 0))
print (binary_to_float)


result = float(literal_eval(float_to_binary))
print (result) #wrong, prints 1078523331.0, should be 3.14

1 个答案:

答案 0 :(得分:2)

这不符合您的想法:

binary_to_float = float(int(float_to_binary, 0))

它不会重新解释数据,而是将整数转换为float,例如12341234.0

你可以使用:

>>> from struct import *
>>>
>>> # float -> binary
>>> bin( unpack('I', pack('f', 3.14))[0] )
'0b1000000010010001111010111000011'
>>>
>>>
>>> # binary -> float
>>> unpack('f', pack('I', 0b1000000010010001111010111000011) )[0]
(3.140000104904175,)
>>>