gpt4 book ai didi

python - float 转二进制

转载 作者:太空狗 更新时间:2023-10-29 22:00:16 25 4
gpt4 key购买 nike

我正在尝试将 float 转换为二进制表示;我怎样才能做到这一点?但是,我的目标是不受 2m 的限制,因此我希望可以轻松扩展到任何基数 (3、4、8) ecc。

到目前为止,我对整数有一个简单的实现:

import string

LETTER = '0123456789' + string.ascii_lowercase
def convert_int(num, base):
if base == 1:
print "WARNING! ASKING FOR BASE = 1"
return '1' * num if num != 0 else '0'

if base > 36: raise ValueError('base must be >= 1 and <= 36')

num, rest = divmod(num, base)
rest = [LETTER[rest]]
while num >= base:
num, r = divmod(num, base)
rest.append(LETTER[r])
rest.reverse()
return (LETTER[num] if num else '') + ''.join(str(x) for x in rest)

感谢任何帮助:)

编辑:

def convert_float(num, base, digits=None):
num = float(num)
if digits is None: digits = 6

num = int(round(num * pow(base, digits)))
num = convert_int(num, base)
num = num[:-digits] + '.' + num[:digits]
if num.startswith('.'): num = '0' + num
return num

是吗?为什么我会出现这种行为?

>>> convert_float(1289.2893, 16)
'509.5094a0'
>>> float.hex(1289.2983)
'0x1.42531758e2196p+10'

附注 How to convert float number to Binary?

我读过那个讨论,但我没有得到答案。我的意思是,它只适用于 0.25、0.125 吗?而且我不明白“必须按相反顺序”这句话...

最佳答案

对于 float ,有内置方法 hex()。

http://docs.python.org/library/stdtypes.html#float.hex

它为您提供给定数字的十六进制表示。从十六进制到二进制的转换是微不足道的。

例如:

In [15]: float.hex(1.25)
Out[15]: '0x1.4000000000000p+0'

In [16]: float.hex(8.25)
Out[16]: '0x1.0800000000000p+3'

关于python - float 转二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4838994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com