Search code examples
pythonfloating-point

Creating floats from binary value in Python


I'm currently working on a project which requires me to modify bit values of float variables. To do this, I am using the struct package to acquire the binary values of a float as a string, like so:

num = -5.661166216897089
s = struct.pack('!f', num)
b = ''.join(format(c, '08b')for c in s)

I will then modify the desired bits with splicing. My question is:

After modifying the string of bits as needed, how can I use it to create a new float value with the modified bit sequence? Defining it as such:

new_float = 0b11000000101101010010100001000110

does not work, I suspect as it is being interpreted as an integer. Is there a way to force float creation?

Thanks ^^


Solution

  • From b you create a new str, v by changing some bits of b. For example:

    v='11001110101101010010100001000110'
    

    Now, you can convert that to bytes:

    v_bytes = bytes([int(v[i:i+8], 2) for i in range(4)])
    

    Which looks like:

    print(v_bytes)
    b'\xce\x9d:u'
    

    and that can be given to struct.unpack:

    new_num = struct.unpack("!f", v_bytes)[0]
    

    unpack returns a tuple, that's why you must take its first element with [0].