Python: flip a bit in a float
Question: I would like to flip a specific bit in a float in Python. It seems to be quite difficult, because the operand | works only for int.

For now I have tried to convert a float into a int: [Get the "bits" of a float
in Python?](http://stackoverflow.com/questions/14431170/get-the-bits-of-a-
float-in-python) But the proposed solution seems not working for too large
float.


Answer: Use `struct.pack` and `struct.unpack`. This is tested under Python 3. There
may be differences for Python 2, consult the doc.

    
    
    >>> 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 requires the exact right length of string for the format. If you are
working along a buffer you can use `unpack_from( fmt, buffer, offset)` where
`offset` defaults to 0 and the requirement is that `buffer` is _at least_ long
enough.

