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.
source
share