是否在C标准中定义了将负double转换为unsigned int的行为? ARM与x86上的不同行为 [英] Is the behaviour of casting a negative double to unsigned int defined in the C standard? Different behaviour on ARM vs. x86

查看:202
本文介绍了是否在C标准中定义了将负double转换为unsigned int的行为? ARM与x86上的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在不同平台上运行的代码,它们似乎获得了不同的结果。我正在寻找适当的解释。

I have code that runs on different platforms that seems to get different results. I am looking for a proper explanation.

我希望强制转换为 unsigned 对于 float double 就像 int 1

I expected casting to unsigned to work the same for float or double as for int1.

Windows:

double dbl = -123.45; 
int d_cast = (unsigned int)dbl; 
// d_cast == -123

WinCE(ARM):

double dbl = -123.45; 
int d_cast = (unsigned int)dbl; 
// d_cast == 0

编辑:

感谢您指出正确的方向。

Thanks for pointing in the right direction.

修复解决方法

fix workaround

double dbl = -123.45; 
int d_cast = (unsigned)(int)dbl; 
// d_cast == -123
// works on both. 






脚注1:编者注:将输出转换为范围 unsigned 值到像 int 这样的有符号类型的值是实现定义的(不是未定义的)。 C17 6.3.1.3-3。


Footnote 1: Editor's note: converting an out-of-range unsigned value to a signed type like int is implementation defined (not undefined). C17 § 6.3.1.3 - 3.

因此, d_cast 的分配也未通过(unsigned)dbl 最终在某些特定实现上具有巨大的积极价值。 (该执行路径包含UB,因此ISO C在理论上已经不在了之列)。实际上,编译器会在普通2的补码机上执行我们期望的操作,并使位模式保持不变。

So the assignment to d_cast is also not nailed down by the standard for cases where (unsigned)dbl ends up being a huge positive value on some particular implementation. (That path of execution contains UB so ISO C is already out the window in theory). In practice compilers do what we expect on normal 2's complement machines and leave the bit-pattern unchanged.

推荐答案






此转换是不确定的,因此不可移植。

No


This conversion is undefined and therefore not portable.

C99 / C11 6.3 .1.4

C99/C11 6.3.1.4


当实数浮点型的有限值转换为_Bool以外的整数类型时,
的小数部分为丢弃(即,该值被截断为零)。如果整数部分的值
无法用整数类型表示,则该行为未定义。

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

根据C11 6.3.1.4脚注61:

According to C11 6.3.1.4 footnote 61:


将整数类型的值转换为无符号类型时执行的余数运算不需要在将值转换为无符号类型时执行实浮点类型的值转换为无符号类型。因此,可移植实际浮点值的范围是(-1,Utype_MAX + 1)。

The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1, Utype_MAX+1).

这篇关于是否在C标准中定义了将负double转换为unsigned int的行为? ARM与x86上的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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