验证C++移位运算符,符号位的溢出效果,符号位的自动扩展与不自动扩展的情况
2012-12-07 15:30
323 查看
C++中的移位运算符<<,>>,移位的效果不是循环移位(如果需要,可用位与、位或人为实现循环移位),其他位数据会丢失。
#include <iostream>
#include <bitset>
#include <string.h>
using namespace std;
int main()
{//移位不是循环移位,会丢失其他位。如果是带符号的,类型转换时会自动扩展符号位;
// 如果是无符号的,类型转换时不会扩展符号位。
unsigned char a = 193;
a = a << 1;
//符号位不自动扩展。
cout << (int)a << endl; //130
a = a << 2;
//符号位溢出
cout << (int)a << endl; //8
char i = 193;
i = i << 1;
//符号位自动扩展
cout << (int)i << endl; //-126
i = i << 2;
//符号位溢出
cout << (int)i << endl; //8
char j = 193;
j = j >> 1;
//右移时符号位扩展。
cout << (int)j << endl; //-32
unsigned char k = 193;
k = k >> 1;
//无符号类型右移时符号位不自动扩展。
cout << (int)k << endl; //96
return 0;
}
#include <iostream>
#include <bitset>
#include <string.h>
using namespace std;
int main()
{//移位不是循环移位,会丢失其他位。如果是带符号的,类型转换时会自动扩展符号位;
// 如果是无符号的,类型转换时不会扩展符号位。
unsigned char a = 193;
a = a << 1;
//符号位不自动扩展。
cout << (int)a << endl; //130
a = a << 2;
//符号位溢出
cout << (int)a << endl; //8
char i = 193;
i = i << 1;
//符号位自动扩展
cout << (int)i << endl; //-126
i = i << 2;
//符号位溢出
cout << (int)i << endl; //8
char j = 193;
j = j >> 1;
//右移时符号位扩展。
cout << (int)j << endl; //-32
unsigned char k = 193;
k = k >> 1;
//无符号类型右移时符号位不自动扩展。
cout << (int)k << endl; //96
return 0;
}
相关文章推荐
- 编程中无穷大的设定 很多人可能设为0x7fffffff,这个数的确是32-bit int的最大值,符号位为0,其他的都是1 但在很多情况下,0x7fffffff会出现错误,比如溢出,这样两个无穷大数相
- c++和c#求摸操作符号%的注意问题,是负数的情况
- text-overflow实现文字超出宽度,溢出后自动显示为省略号的效果
- 【C++专题】数值二进制表示、补码、反码、有符号数、无符号数、小数、有符号数的扩展
- [原创]采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
- 采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
- C++ 带符号和无符号char类型赋值超出表示范围的情况
- 自动在c++中插入成员函数 (emacs 扩展)
- Visual C++ 编译器自动假定带 .C 扩展名的文件是 C 文件而不是 C++ 文件,并且拒绝 C++ 语法和关键字(c语言只能在大括号最前面申明变量)
- 在验证模式为Forms的情况下,如何解决自动登录问题. (已解决)
- 用页面脚本扩展mvc自动添加的验证
- 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展
- text-overflow实现文字超出宽度,溢出后自动显示为省略号的效果
- Java 中没有无符号数,在读字节数组转换的时候需要注意溢出的情况
- C++系统自动生成默认构造函数的情况
- 调试web service的问题:“无法自动进入并单步执行服务器。无法确定停止位置。请验证是否已加载符号。未找到符号:……”
- [原创]采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
- 64位无符号溢出后差1的问题: UINT(-3) + UINT64(5) ) % UINT64(5) 竟然等于了3 (后续避免使用UINT 溢出效果)
- 采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
- 使用Xcode阅读Makefile管理的C/C++项目源码(支持调试,符号跳转,自动补全)