C/C++ 位操作 总结
生活随笔
收集整理的這篇文章主要介紹了
C/C++ 位操作 总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
| 1? | ? |
| 2? | #include?<bitset> |
| 3? | #include?<iostream> |
| 4? | #include?<string> |
| 5? | #include?<limits> |
| 6? | ? |
| 7? | using?namespace?std; |
| 8? | ? |
| 9? | 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? | } |
轉載于:https://www.cnblogs.com/dyufei/archive/2010/11/20/2573908.html
總結
以上是生活随笔為你收集整理的C/C++ 位操作 总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 30、驱动程序调用驱动程序
- 下一篇: sharepoint 2010学习资源汇