Reputation: 11
I read signed fractional value from sensor in q16.4 format and receive this value through i2c bus as unsigned long. I want to convert this value to float to perform algorithm. I was trying to convert it to float like this:
float vOut = (float)read_data * 65536;
with no result. Data look like is still unsigned long
with point. Can you give my advice what will be the best way to convert it correctly?
Upvotes: 0
Views: 607
Reputation: 153457
Sorry, not more detail GTG.
uint8_t tab[3];
Read_sensor(tab);
unsigned long ul = tab[0];
ul <<= 8;
ul |= tab[1];
ul <<= 4;
ul |= tab[2] & 0xF;
// I am fuzzy on q16.4 format, so some assumptions.
// Assuming Bit 19 is the sign bit and data is sign-magnitude
float x = ul & 0x7FFFFL;
x /= 16.0f;
if (ul & 0x80000L) {
x = -x;
}
Upvotes: 1
Reputation: 15501
Try:
float vOut = read_data;
vOut /= 16.0f;
Dividing by 16 pushes the four fractional bits of the fixed point number into the fractional bits of the float.
Upvotes: 3