Search code examples
pythonieee-754floating-point-conversion

convert unsigned integer to float in python


I wrote a socket server that reads data from some devices. After reading data binary shift is applied on bytes. After that i get an integer value for instance 1108304047 and i want to convert this number to IEEE 754 float 35.844417572021484. I found some solutions with struct.unpack but it doesn't seem to me rational. First we convert number to string then convert to float.

Is there any short way like Float.intBitsToFloat(1108304047) in Java.

The solution that i found with struct.unpack is quite long. it contains string conversion, sub string fetching, zero filling etc..

def convert_to_float(value):

    return struct.unpack("!f", hex(value)[2:].zfill(8).decode('hex'))[0]

Solution

  • As you can see in Java they are using structure to do the trick.

    /*
     * Find the float corresponding to a given bit pattern
    */
    JNIEXPORT jfloat JNICALL
    Java_java_lang_Float_intBitsToFloat(JNIEnv *env, jclass unused, jint v)
    {
        union {
            int i;
            float f;
        } u;
        u.i = (long)v;
        return (jfloat)u.f;
    }
    

    In Python it is not possible to do this way, hence you need to use the struct library

    This module performs conversions between Python values and C structs represented as Python strings

    First the number is converted to representation of long

    packed_v = struct.pack('>l', b)
    

    and then is unpacked to float

    f = struct.unpack('>f', packed_v)[0]
    

    That's similar as in Java.

    def intBitsToFloat(b):
       s = struct.pack('>l', b)
       return struct.unpack('>f', s)[0]
    

    Please correct me if I'm wrong.