Search code examples
c++floating-pointuint8tuint16

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


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?


Solution

  • 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.