title: Python: flip a precise bit in a double
body: <p>I need to flip a precise bit in a double with Python.</p>
  
  <p>More precisely, I need a function that takes as arguments the double X and the position i and return the corrupted value of X, in which the i-th bit in the double-precision has been flipped.</p>
  
  <p>For example: <code>bitflip(34.501,63)</code> should return <code>-34.501</code> (the last bit is the sign).</p>
  
  <p>For now, I have got this function:</p>
  
  <pre><code>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 &lt;&lt; r
      fs = pack('BBBBBBBB', *bval)
      fnew=unpack('d',fs)
      return fnew[0]
  </code></pre>
  
  <p>But it doesn't flip the i-th bit.</p>