Search code examples
pythonfloating-point-conversion

Convert a list of ints to a float


I am trying to convert a number stored as a list of ints to a float type. I got the number via a serial console and want to reassemble it back together into a float. The way I would do it in C is something like this:

bit_data = ((int16_t)byte_array[0] << 8) | byte_array[1];
result = (float)bit_data;

What I tried to use in python is a much more simple conversion:

result = int_list[0]*256.0 + int_list[1]

However, this does not preserve the sign of the result, as the C code does. What is the right way to do this in python?

UPDATE: Python version is 2.7.3. My byte array has a length of 2. in the python code byte_array is list of ints. I've renamed it to avoid misunderstanding. I can not just use the float() function because it will not preserve the sign of the number.


Solution

  • I'm a bit confused by what data you have, and how it is represented in Python. As I understand it, you have received two unsigned bytes over a serial connection, which are now represented by a list of two python ints. This data represents a big endian 16-bit signed integer, which you want to extract and turn into a float. eg. [0xFF, 0xFE] -> -2 -> -2.0

    import array, struct
    
    two_unsigned_bytes = [255, 254] # represented by ints
    byte_array = array.array("B", two_unsigned_bytes) 
    # change above to "b" if the ints represent signed bytes ie. in range -128 to 127
    signed_16_bit_int, = struct.unpack(">h", byte_array)
    float_result = float(signed_16_bit_int)