How can I convert uint8_t and uint16_t into floats in c++?

Eneko picture Eneko · Sep 10, 2014 · Viewed 22.5k times · Source

I created uint8_t and uint16_t variable types and read values into them from some registers. But, I'm unsure if I can easily cast these into float, and if the conversion will make numeric sense.

What is the optimal way to cast uint8_t, and uint16_t, into float?

Answer

Mike Seymour picture Mike Seymour · Sep 10, 2014

There's no need to cast; integer types are implicitly convertible to floating-point types.

uint8_t u8 = something;
uint16_t u16 = whatever;

float f1 = u8;
float f2 = u16;

8 and 16-bit integer values should be represented exactly. Larger types might lose some precision.