double到unsigned int/char [英] double to unsigned int / char

查看:94
本文介绍了double到unsigned int/char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处读到:

根据C99§6.3.1.4脚注50:

According to C99 §6.3.1.4 footnote 50:

当整数类型的值是当值为real时,无需执行转换为unsigned类型的转换浮动类型转换为无符号类型.因此,范围可移植的实际浮点值为(−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 ++ 03 !)感兴趣:

Now, I am interested in the subtle difference (this time for C++ 03!) between:

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,还是有其他规则?

So the first c1 and the second c1 are not guaranteed to compare as equal, right? Is the citation from above also valid for C++03, or are there other rules?

并且为了定义 c2 (对于-(2 ^ 31-1)< = d2< 0 ),是否有必要这样做?

and for making c2 defined (for -(2^31-1) <= d2 < 0) would this be necessary to do?

double d2 = -2;
int sign = (d2<0 ? -1 : 1);

unsigned char c2 = sign * (int)abs(d2); // defined, c2 == 2^8-2 ?

推荐答案

是的,相同的规则适用于C ++.(但是,我要使用2010年的C ++标准草案; C ++ 2003是旧的.而且,我使用的是N3092,而不是正式的草案.)第4.9条第1款规定:如果不能将截断的值设为0,则行为是不确定的以目标类型表示."

Yes, the same rule applies for C++. (However, I am going by a 2010 draft of the C++ standard; C++ 2003 is old. Also, I am using N3092, not the official draft.) Clause 4.9, paragraph 1 says "The behavior is undefined if the truncated value cannot be represented in the destination type."

无符号整数运算会自动换行;它以模1的形式执行,而不是该类型的最大值.但是,这适用于类型内的算术.从浮点到无符号整数的转换不是其中的一部分.

Unsigned integer arithmetic does wrap; it is performed modulo 1 more than the maximum value of the type. However, this applies to arithmetic within the type. Conversion from floating-point to unsigned integer is not part of this.

您用于转换 d2 的代码似乎比必要的复杂.如果 d2 int 的范围内,则可以简单地使用 unsigned char c2 =(int)d2; .(尽管从 int unsigned int 的转换也在同类无符号整数算法之外,但此转换的规范确实说,它的减少方式与无符号整数算法相同.)

Your code for converting d2 seems more complicated than necessary. If d2 is within the range of an int, you could simply use unsigned char c2 = (int) d2;. (Although conversion from int to unsigned int is also outside homogeneous unsigned integer arithmetic, the specification for this conversion does say it is reduced the same way unsigned integer arithmetic is.)

这篇关于double到unsigned int/char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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