Posts Tagged ‘C’

Two 16bit integers that represent one 32bit float

April 24, 2012 3 comments

Recently I came across the following problem…

There was a function that could read from some device’s registers and return their values as uint16_t. The problem was that each two 16bit registers in sequence (reg[0] and reg[1], reg[2] and reg[3], etc) were storing a 32bit float number (in little endian).

The first thing that came into my mind was to concatenate the data

integer_32 = ((integer_16_2 & 0xFFFF) << 16) | (integer_16_1 & 0xFFFF)

and produce a 32bit integer. Then this 32bit integer would be casted to a float.

Nevertheless, this is not correct because the bits of the registers were representing a float and not an integer. So if we produced lets say the integer_32 “3” the float that would be generated would be “3.0” and not the float that is represented by the binary “11”.

The solution to this problem was the following:

#include <string.h>

 * Reform two 16bit unsigned integers that store one 32bit
 * signed float (little endian).
 * @param u1 the first 16bit unsigned
 * @param u2 the second 16bit unsigned
 * return the 32bit float
float reform_uint16_2_float32(uint16_t u1, uint16_t u2)
    long int num = ((u2 & 0xFFFF) << 16) | (u1 & 0xFFFF);
    float numf;
    memcpy(&numf, &num, 4);
    return numf;
Categories: Programming Tags: