Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

downcasting a double/float to a uint8_t

Let’s say I have the following bit of code, which tries to ‘downcast’ a double value into a uint8_t:

uint8_t downcast(uint8_t *down1, uint8_t *down2)
{
    //the usual nullptr checks
    double fval = 100.0; //fits the uint8_t domain range
    *down1 = (uint8_t)fval;  //should work...

    fval = 1000.0; //does not fit uint8_t domain range
    *down2 = (uint8_t)fval;  //will this work??
}

I’ve seen a few posts that suggest doing this sort of "quantization-cast", but I’m not sure this is correct. I seem to recall reading that a double var whose value exceeds the output domain, will lead to undefined behavior from the cast (either C or static_cast<uint8_t>(fval)).

Thoughts?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The behaviour of the second cast is undefined.

C17 §6.3.1.4 ¶1 When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading