从double到无符号64位整数的安全转换 [英] Safe conversion from double to unsigned 64 bit integer

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

问题描述

在我的平台上,这将打印9223372036854775808.

On my platform this prints 9223372036854775808.

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

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

I tried Boost.NumericConversion, but got the same result.

x 分成两等份,然后将转换后的两半加在一起即可得出正确的结果.但是我需要在模板代码中使用通用解决方案.

Splitting x into 2 equal part, then adding together converted halves give the correct result. But I need a generic solution to use in a template code.

谢谢.

在Visual Studio 2008上显示此问题,但在MinGW上没有.将4.0e9强制转换为无符号的long效果很好.

This problem shows up on Visual Studio 2008, but not MinGW. Casting 4.0e9 into unsigned long works fine.

推荐答案

似乎可以在gcc上很好地工作,但是在Visual Studio中却是有问题的.有关此问题,请参见 Microsoft的答案:

Seems like it works well with gcc, but it is problematic in Visual Studio. See Microsoft's answer regarding this issue:

我们的浮点数到整数转换总是完成有符号整数.在这个特别的如果我们使用FIST指令如您所述生成800..00.因此,没有定义转换为无符号的行为64位整数值是大于最大的64位有符号整数.

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).

So you can only convert the numbers in the signed 64-bit integer range: −9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (-2^63~2^63-1).

这篇关于从double到无符号64位整数的安全转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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