在我的平台上打印出 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/