gpt4 book ai didi

python - 在 Python 中将 float.hex() 值转换为二进制

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

我想知道如何将 float.hex() 返回的结果转换为二进制,例如,从 0x1.a000000000000p+2110.1.

有人可以帮忙吗?谢谢。

最佳答案

def float_to_binary(num):
exponent=0
shifted_num=num
while shifted_num != int(shifted_num):
shifted_num*=2
exponent+=1
if exponent==0:
return '{0:0b}'.format(int(shifted_num))
binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
integer_part=binary[:-exponent]
fractional_part=binary[-exponent:].rstrip('0')
return '{0}.{1}'.format(integer_part,fractional_part)

def floathex_to_binary(floathex):
num = float.fromhex(floathex)
return float_to_binary(num)


print(floathex_to_binary('0x1.a000000000000p+2'))
# 110.1

print(floathex_to_binary('0x1.b5c2000000000p+1'))
# 11.01101011100001

解释:

float.fromhex 返回一个 float num。我们想要它的二进制表示。

{0:b}.format(...) 返回整数的二进制表示,但不返回 float 。

但是如果我们将 float 乘以足够多的 2 次方,即将二进制表示向左移动足够多的位置,我们最终会得到一个整数,shifted_num

一旦我们有了那个整数,我们就可以自由回家了,因为现在我们可以使用 {0:b}.format(...)

我们可以根据向左移动的位数(指数)使用一些字符串切片来重新插入小数点(呃,二进制小数点?)。

技术要点:shifted_num 的二进制表示中的位数可能小于exponent。在这种情况下,我们需要在左侧用更多的 0 填充二进制表示,因此使用 binary[:-exponent] 的二进制切片不会为空。我们使用 '{0:0{1}b}'.format(...) 进行管理。格式字符串中的 0{1} 将格式化字符串的宽度设置为 {1},并在左侧用零填充。 ({1} 被替换为数字 exponent。)

关于python - 在 Python 中将 float.hex() 值转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7666713/

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