[cfp-interest 3947] Re: Weird Casting Error
Fred J. Tydeman
tydeman at tybor.com
Wed Jun 10 05:44:11 PDT 2026
On Wed, 10 Jun 2026 10:14:06 +1000 (AEST) Damian McGuckin wrote:
>
>Because of my fat fingers and a jumbled brain, my casting of a signed floating point number to an unsigned integer
>showed a logic problem. E.g.
>
> const uint32_t k = (uint32_t) x;
>
>produces rubbish if x is negative. I really meant to type
>
> const int32_t k = (int32_t) x;
>
>Silly me.
>
>Mind you, if x can be guaranteed positive, it is perfectly legitimate. But if not, it is cause of a subtle bug.
>
>Why does C allow a cast from a signed floating point datum to an unsigned integer datum when that primitive does not
>exist in IEEE 754. Is it purely historical. Just curious.
C23 has:
6.3.1.4 Real floating and integer
When a finite value of standard 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.
My guess: If the floating point value is positive, it makes sense. Also, unsigned int types
have twice the positive range than the corresponding signed int type.
And, the main part of the C standard applies to more than IEEE-754.
---
Fred J. Tydeman Tydeman Consulting
tydeman at tybor.com Testing, numerics, programming
+1 (702) 608-6093 Vice-chair of INCITS/C (ANSI "C")
Sample C17+FPCE tests: http://www.tybor.com
Savers sleep well, investors eat well, spenders work forever.
More information about the cfp-interest
mailing list