DYF
我思故我在!

 
#include <bitset>
#include <iostream>
#include <string>
#include <limits>
 
using namespace std;
 
int main(int argc, char* argv[])
10  {
11      cout<<"==移位操作===================="<<endl;
12      //左移/右移n位将所有位向左/右移动n位,腾出来的位置补零,超出边界的位置被丢弃。相当于乘以/除以2的n次方。
13      int x=20;
14      int y=x<<3;
15      cout<<y<<endl;
16      cout<<hex<<y<<endl;
17      y=y>>3;
18      cout<<y<<endl;
19      y=y>>3;
20      cout<<y<<endl<<endl;
21      //打开指定位(将指定位设置为1):将该数的第n位于1或。
22      //通过移位运算符来构造掩码,将1左移n-1位,然后于该数或。
23      cout<<"==1:将指定位设置为1===================="<<endl;
24      int lottabits= 5,bit=16,xbit,c,j,k=4;
25      xbit = (~bit);
26      c=lottabits|bit;
27      j=lottabits;
28      j|= 1<<k;
29      bitset<32> bita(lottabits); 
30      bitset<32> bitb(bit);
31      bitset<32> bitc(c);
32      bitset<32> bitd(j);
33      bitset<32> bitx(xbit);
34   
35      cout <<"5 bits  is: "<<bita<<endl<<"16 bits is: "<<bitb<<endl<<"5|16    is: "<<bitc<<endl;
36      cout <<"5|=1<<4 is: "<<bitd<<endl<<endl; 
37      //切换指定位(将原来的0置为1,原来的1置为0):将该数的指定位于1异或。
38      //
39      cout<<"==2:切换指定位===================="<<endl;
40      c=lottabits^bit;
41      bitset<32> bitm(c);
42      cout <<"5 bits  is: "<<bita<<endl<<"15 bits is: "<<bitb<<endl<<"5|15    is: "<<bitm<<endl<<endl; 
43     
44      //关闭指定位(将指定位设置为0):将该数的指定位(第n位)于0于。
45      //通过移位构造掩码,将1左移n-1位,然后取反 再于该数相与。
46      cout<<"==3:关闭指定位===================="<<endl;
47      int i=4;
48      i=(~i);
49      c=lottabits&i;
50      j=lottabits;
51      j &= ~(1<<2);
52      bitset<32>    bith(c);
53      bitset<32>    bitj(j);
54      bitset<32>    biti(i);
55      cout <<"5  bits  is: "<<bita<<endl<<"~4  bits is: "<<biti<<endl<<"5 &(~15) is: "<<bith<<endl; 
56      cout <<"5&(~(1<<2)): "<<bitj<<endl<<endl;
57   
58      //测试指定位(确定将指定位中对应位是否为1):将该数的指定位于1于操作,返回值不变。即lottabits&bit ==bit或 if(lottabits&bit)。
59      //if(lottabits&1<<n-1)
60      cout<<"==4:测试指定位===================="<<endl;
61      c=lottabits&bit;
62      bitset<32> bitf(c);
63      cout <<"5  bits  is: "<<bita<<endl<<"~15 bits is: "<<bitb<<endl<<"5 &(~15) is: "<<bitf<<endl<<endl; 
64      cout<<"======================"<<endl;
65  }
posted on 2010-11-20 00:00  o(∩_∩)o...  阅读(364)  评论(0编辑  收藏  举报