您的位置:首页 > 编程语言 > C语言/C++

验证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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐