验证C++移位运算符,符号位的溢出效果,符号位的自动扩展与不自动扩展的情况

来源:互联网 发布:二战历史类书籍 知乎 编辑:程序博客网 时间:2024/06/05 05:12

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;
}

 

原创粉丝点击