64位double到int转换问题 [英] 64-bit double to int conversion problem

查看:222
本文介绍了64位double到int转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个无法解释的奇怪问题,尽管我是一位经验丰富的C ++程序员.使用VC ++编译时,以下代码无法正常工作 64位:

double dbl = 4294965732.000000;
int n =(int)dbl;
n变量应包含-1564,并且在使用32位编译器进行编译时会执行此操作.但是64位编译器会产生2147483648(0x80000000).

我通过添加代码来解决问题
#ifdef _WIN64
__ int64 temp = dbl;
n = temp;
#endif
,但不希望诉诸于这种方式.
谢谢.

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.

推荐答案

根据已编译的代码,转换基于 cvttsd2si 指令以及32位目标操作数,并且根据制造商的文档, 如果转换后的结果大于最大有符号双字整数,则会引发浮点无效异常.如果屏蔽了此异常,则返回不确定的整数值(80000000H)..因此它返回0x80000000,即–2147483648.

According to compiled code, the conversion is based on cvttsd2si instruction with 32-bit destination operand, and, from manufacturer’s Documentations, "If a converted result is larger than the maximum signed doubleword integer, the floating point invalid exception is raised. If this exception is masked, the indefinite integer value (80000000H) is returned". So it returns 0x80000000, which is –2147483648.

如果转换为64位整数,则不会发生错误.然后,当将4294965732LL截断为32位整数时,将得到预期的–1564.


这篇关于64位double到int转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆