c++ - 从 double 到无符号 64 位整数的安全转换

标签 c++ c

在我的平台上打印出 9223372036854775808。

double x = 1e19;
std::cout << static_cast<unsigned __int64>(x) << '\n';

我尝试了 Boost.NumericConversion,但得到了相同的结果。

x 分成两等份,然后将转换后的两半相加得到正确的结果。但是我需要一个通用的解决方案来在模板代码中使用。

提前谢谢你。

编辑: 此问题出现在 Visual Studio 2008 上,但未出现在 MinGW 上。将 4.0e9 转换为 unsigned long 效果很好。

最佳答案

似乎它在 gcc 中运行良好,但在 Visual Studio 中存在问题。参见 Microsoft's answer关于这个问题:

Our floating-point to integer conversions are always done to a signed integer. In this particular case we use FIST instruction which generates 800..00 as you described. Therefore, there is no defined behavior for converting to unsigned 64-bit integer values which are larger than largest 64-bit signed integer.

因此只能将带符号的 64 位整数范围内的数字:−9,223,372,036,854,775,808 转换为 +9,223,372,036,854,775,807 (-2^63~2^63-1)。

关于c++ - 从 double 到无符号 64 位整数的安全转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3332440/

相关文章:

c - 尾递归 [C]

c - 将字符串中的字符替换为 C 中的字符串

c++ - fatal error : filesystem: No such file or directory

c++ - mfc 从另一个对话框更改一个对话框的光标

c - Linux UDP 套接字/端口重用

c - 无法循环遍历c pos中的数据

c++ - 关于 boost::unique_future 的文档

c++ - 堆喷射攻击是如何工作的?

c++ - const char* 有什么异常(exception)吗?

c - 如果在调用 pthread_cond_wait() 之后,另一个线程获取了被锁定的互斥锁,然后调用 phread_cond_broadcast 会发生什么情况?