level 5
文章上说c++中把负值赋给unsigned对象是完全合法的,其结果是该负数对该类型的取值个数求模后的值。所以,如果把-1赋给8位的unsigned char那么结果是255.因为255是-1对256求模后的值求解
2012年03月15日 04点03分
1
level 5
#include<iostream>
using namespace std;
int main ()
{
cout<<-1%256<<endl;
return 0;
}
2012年03月15日 04点03分
5
level 5
(-1+256)%256这个应该是不同类型求模得时候用的吧。。如果是同是int类型的-1%256编译器显示为-1
2012年03月15日 04点03分
10
level 5
#include<iostream>
using namespace std;
int main ()
{ unsigned char i=-1;
cout<<i<<endl;
return 0;
}我用编译器运行了下
无结果显示
2012年03月15日 04点03分
11
level 5
我发现如果这样求模得到的数如果和ASCII码的某个字符10进制数相等他就输出,如果不是他就不输出
2012年03月15日 04点03分
12
level 5
如果同是int类型 -1%256就是值就是-1没越界,
2012年03月15日 04点03分
15
level 15
implementation-defined,不见得要按补码,尽管大多数情况下都是。
2012年03月15日 04点03分
16
level 15
转换也是implementation-defined,翻编译器文档去。
2012年03月15日 04点03分
17
level 15
不是。语言和实现相关。C89/C++03和C99/C++11对含有负数的模除的规定有变。参考en.喂鸡百科.org/wiki/Modulo_operation。
2012年03月15日 04点03分
19
level 15
类型表示不是implementation-defined behavior,但实际上选择哪一种是至少unspecified。
ISO C++11
3.9.1
7 Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.48 A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system.49 [ Example: this International Standard permits 2’s complement, 1’s complement and signed magnitude representations for integral types. —end example ]
而无符号整数向有符号数转换是明确的implementation-defined behavior:
ISO C++11
4.7
3 If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
Index of implementation-defined behavior
value of result of unsigned to signed conversion, 84
2012年03月15日 05点03分
20