你如何設(shè)置,清除和切換一個位?如何在C / C ++中設(shè)置,清除和切換?
3 回答

神不在的星期二
TA貢獻1963條經(jīng)驗 獲得超6個贊
使用標準C ++庫:std::bitset<N>
。
或Boost版本:boost::dynamic_bitset
。
沒有必要自己動手:
#include <bitset>#include <iostream>int main(){ std::bitset<5> x; x[1] = 1; x[2] = 0; // Note x[0-4] valid std::cout << x << std::endl;}
[Alpha:] > ./a.out00010
與標準庫編譯時大小的bitset相比,Boost版本允許運行時大小的bitset。

人到中年有點甜
TA貢獻1895條經(jīng)驗 獲得超7個贊
另一種選擇是使用位字段:
struct bits { unsigned int a:1; unsigned int b:1; unsigned int c:1;};struct bits mybits;
定義一個3位字段(實際上,它是三個1位字符)。位操作現(xiàn)在變得有點(哈哈)更簡單:
設(shè)置或清除一下:
mybits.b = 1;mybits.c = 0;
要切換一下:
mybits.a = !mybits.a;mybits.b = ~mybits.b;mybits.c ^= 1; /* all work */
檢查一下:
if (mybits.c) //if mybits.c is non zero the next line below will execute
這僅適用于固定大小的位字段。否則你必須采用之前帖子中描述的比特技巧。
- 3 回答
- 0 關(guān)注
- 758 瀏覽
添加回答
舉報
0/150
提交
取消