获取数字(int,float或double的binary32表示形式的Python方法)

问题描述 投票:0回答:1

关于Python int to binary string?,我想知道一种Python方式来获取多个int,float或double的IEEE-754 binary32表示形式。

例如,将42.0转换为1 10000100 01010 000000000000000000

python python-3.x floating-point ieee-754
1个回答
0
投票

尝试一下:

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')
© www.soinside.com 2019 - 2024. All rights reserved.