我读了here ,即:
根据 C99 §6.3.1.4 脚注 50:
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++ 03!):
double d1 = 257;
double d2 = -2;
unsigned char c1 = d1; // undefined, since d1 > 256
unsigned char c2 = d2; // undefined, since d2 < -1
和
double d1 = 257;
double d2 = -2;
unsigned int i1 = d1; // defined, since d1 <= 2^32
unsigned int i2 = d2; // still undefined, right?
unsigned char c1 = i1; // defined, modulo 2^8, so c1 == 1
所以第一个c1
第二个c1
不能保证比较相等,对吗?上面的引用是否对 C++03 也有效,还是有其他规则?
编辑:
并制作c2
已定义(对于 -(2^31-1) <= d2 < 0
)是否有必要这样做?
double d2 = -2;
int sign = (d2<0 ? -1 : 1);
unsigned char c2 = sign * (int)abs(d2); // defined, c2 == 2^8-2 ?
最佳答案
是的,同样的规则适用于 C++。 (但是,我正在使用 C++ 标准的 2010 草案;C++ 2003 很旧。另外,我使用的是 N3092,而不是官方草案。)第 4.9 条第 1 段说“如果不能截断值,则行为未定义”以目标类型表示。”
无符号整数运算确实换行;它比类型的最大值以 1 为模执行。但是,这适用于类型内的算术。从 float 到无符号整数的转换不在其中。
您转换 d2
的代码似乎比必要的更复杂。如果 d2
在 int
的范围内,您可以简单地使用 unsigned char c2 = (int) d2;
。 (尽管从 int
到 unsigned int
的转换也在齐次无符号整数算法之外,但此转换的规范确实说明它的缩减方式与无符号整数算法相同。)
关于c++ - double 到 unsigned int/char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660250/