"When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined."
See it says implementation-defined manner, not according to the current rounding mode.
Test case:
#pragma STDC FENV_ACCESS ON
#include <stdio.h>
#include <stdint.h>
#include <fenv.h>
int main()
{
fesetround(FE_DOWNWARD);
printf("%f\n", (double)UINT64_MAX);
fesetround(FE_UPWARD);
printf("%f\n", (double)UINT64_MAX);
return 0;
}
$ gcc -std=c99 -frounding-math x.c -lm
$ ./a.out
18446744073709551616.000000
18446744073709551616.000000
In both cases it rounded up. bool double_to_uint64 (double x, uint64_t *out)
{
double y = trunc(x);
if (y >= 0.0 && y < ldexp(1.0, 64)) {
*out = y;
return true;
} else {
return false;
}
}
If you need different rounding behavior, just change trunc() to round(), floor() or ceil(). Note that it is important that the result is produced by converting the rounded double (y) to an integer type, not the original value (x).Explanation:
- we first round the value to an integer (but still a floating point value),
- we then check that this integer is in the valid range of the target integer type by comparing it with exact integer values (0 and 2^N),
- if the check passes, then converting this integer to the target integer type is safe, and if the check fails, then conversion is not possible.
Of course if you literally need to convert to "long" you have a problem because the width of "long" is not known, but that is a rather different concern. I argue types with unknown width like "long" should almost never be used anyway.
(based on my answer here: https://stackoverflow.com/questions/8905246/how-to-check-if-...)