64-bit double to int conversion

Apr 22, 2014 at 7:34pm
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;
#endif

but would prefer not to resort to kludges like that.

Thanks in advance.
Apr 22, 2014 at 11:51pm
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 Apr 22, 2014 at 11:51pm
Apr 23, 2014 at 3:06am
Have you tried the same result with unsigned int?
Apr 23, 2014 at 10:42am

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.
http://blogs.msdn.com/b/vcblog/archive/2012/10/25/hello-arm-exploring-undefined-unspecified-and-implementation-defined-behavior-in-c.aspx?Redirected=true

The overflow when converting from float to integer is undefined behavior

http://blog.frama-c.com/index.php?post/2013/10/09/Overflow-float-integer

use some kind of floor function, like std::floor
Last edited on Apr 23, 2014 at 11:37am
Topic archived. No new replies allowed.