6

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?

Andrew
  • 1,423
  • 1
  • 17
  • 26
Eneko
  • 149
  • 1
  • 2
  • 13

2 Answers2

14

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Now Seymours answer and Bathsheba's comment are good, but I have recently been hit by a case of C++11 so will try an alternative answer, which might be useful or totally irrelevant for your use of the conversion.

The conversion from integer to float can sometimes takes many cycles!

So if the values you want to convert are only a limited number of the actual values or they are litterals or the compiler can reason that they are constants, there is a (runtime) faster way.

constexpr float ToFloatAtCompileTime(uint8_t u8) {
    return u8; // implicit conversion to return type
}

float f1 = ToFloatAtCompileTime(u8);

Note: your compiler might do this implicitly on higher optimization level.

Surt
  • 15,501
  • 3
  • 23
  • 39