Python: flip exact bit to double

I need to flip the exact bit to double using Python.

More precisely, I need a function that takes double X and the position i as arguments and returns the damaged value of X, in which the i-th bit was turned upside down in double precision.

For example: bitflip(34.501,63)should return -34.501(the last bit is a sign).

Now I have this function:

from struct import *

def bitflip(x,pos):
    fs = pack('d',x)
    bval = list(unpack('BBBBBBBB',fs))
    [q,r] = divmod(pos,8)
    bval[q-1] ^= 1 << r
    fs = pack('BBBBBBBB', *bval)
    fnew=unpack('d',fs)
    return fnew[0]

But he does not flip the i-th bit.

+4
source share
1 answer

I think the problem is here:

bval[q-1] ^= 1 << r
#    ^why q-1?

divmod(1,8) is (0,1) ( - , 0, , 0). q q-1:

from struct import *

def bitflip(x,pos):
    fs = pack('d',x)
    bval = list(unpack('BBBBBBBB',fs))
    [q,r] = divmod(pos,8)
    bval[q] ^= 1 << r
    fs = pack('BBBBBBBB', *bval)
    fnew=unpack('d',fs)
    return fnew[0]

:

>>> bitflip(34.501,63)
-34.501
+2

Source: https://habr.com/ru/post/1623346/


All Articles