Search code examples
pythoncasting

How do I convert a string of a floating point decimal number into a float type?


I have a 32bit floating point decimal in sting format. I want to get it into float format.

For exmaple, how do I convert this string: '01000010000000001110111010011000' into this float: 32.233001709

Perhaps there is some intermediate step where the string is converted into binary: 0b01000010000000001110111010011000?


Solution

  • Adapting my answer from one of the questions posted as a possible duplicate:

    s2 = '01000010000000001110111010011000'
    struct.unpack('f', struct.pack('I', int(s2, 2)))[0]
    

    It's a three-step process. First convert the binary string to int. Second convert that to a sequence of bytes. Third convert those bytes to float.