【发布时间】:2020-03-12 09:45:01
【问题描述】:
与Python int to binary string?相关,我想知道一种pythonic方法来获取整数、浮点数或双精度数的IEEE-754 binary32表示。
例如 42.0 要转换为 1 10000100 01010 000000000000000000
【问题讨论】:
标签: python python-3.x floating-point ieee-754
与Python int to binary string?相关,我想知道一种pythonic方法来获取整数、浮点数或双精度数的IEEE-754 binary32表示。
例如 42.0 要转换为 1 10000100 01010 000000000000000000
【问题讨论】:
标签: python python-3.x floating-point ieee-754
试试这个:
import struct
getBin = lambda x: x > 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
def floatToBinary32(value):
val = struct.unpack('I', struct.pack('f', value))[0]
return getBin(val)
binstr = floatToBinary32(42.0)
print('Binary equivalent of 42.0:')
print(binstr + '\n')
【讨论】: