64-bit double to int conversion

Hello all,

I ran into a strange problem I cannot explain, although I am an experienced C++ programmer. The following code does not work properly when compiled with VC++ 64-bit:

double dbl = 4294965732.000000;
int n = (int)dbl;

The n variable should contain -1564, and it does when this is compiled with a 32-bit compiler. But the 64-bit compiler produces 2147483648 (0x80000000).

I fudged the problem by adding the code

#ifdef _WIN64
__int64 temp = dbl;
n = temp;

but would prefer not to resort to kludges like that.

Thanks in advance.
That results in undefined behaviour; it isn't defined by the language standards. That value could be theoretically anything within the range of int variables.
Last edited on
Have you tried the same result with unsigned int?

On ARM, when you convert a NaN (Not-a-Number) floating point value to an integer type, the result is 0x00000000. On x86 and x64, the result is 0x80000000.

The overflow when converting from float to integer is undefined behavior


use some kind of floor function, like std::floor
Last edited on
Topic archived. No new replies allowed.