Python:在浮动中翻转一点

guh*_*hur 3 python floating-point bit

我想在Python的浮动元素中翻转一个特定的位。这似乎很困难,因为操作数| 仅适用于int。

现在,我尝试将浮点数转换为int:在Python中获取浮点数的“位”吗? 但是建议的解决方案似乎不适用于太大的浮动。

nig*_*222 5

使用struct.packstruct.unpack。这已在Python 3下进行了测试。Python2可能有所不同,请查阅文档。

>>> 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,)
Run Code Online (Sandbox Code Playgroud)

解压缩要求格式的字符串正确正确的长度。如果你是沿着一个缓冲区,则可以使用unpack_from( fmt, buffer, offset)其中offset默认值为0,要求是buffer至少足够长。