gpt4 book ai didi

Python:在 float 中翻转一点

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:22 25 4
gpt4 key购买 nike

我想在 Python 中翻转 float 中的特定位。好像挺难的,因为操作数 |仅适用于 int。

现在我尝试将 float 转换为整数:Get the "bits" of a float in Python?但建议的解决方案似乎不适用于太大的 float 。

最佳答案

使用struct.packstruct.unpack。这是在 Python 3 下测试的。Python 2 可能存在差异,请查阅文档。

>>> from struct import pack,unpack
>>> fs = pack('f',1.0) # pack float ('f') into binary string
>>> fs
b'\x00\x00\x80?'

>>> bval = list( unpack('BBBB', fs)) # use list() so mutable list
>>> bval
[0, 0, 128, 63]
>>> bval[1]=12 # mutate it (byte in middle of mantissa bits)

>>> fs = pack('BBBB', *bval) # back to a binary string after mutation
>>> fs
b'\x00\x0c\x80?'

>>> fnew=unpack('f',fs) # and let's look at that slightly altered float value
>>> fnew # NB it is a tuple of values, just one in this case
(1.0003662109375,)

解包要求格式的字符串长度正确。如果你在缓冲区工作,你可以使用 unpack_from(fmt, buffer, offset) 其中 offset 默认为 0 并且要求是 buffer 至少足够长。

关于Python:在 float 中翻转一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615590/

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