搜尋此網誌

2009年7月20日 星期一

bit 運算

bit的運算其實沒啥了不起,但除非是作跟硬體相關的程式設計,用到的機會還真是不多.
但很不巧的是,有時就是偏偏會碰上,更不巧的是.因為很少碰.所以也就不知道該怎麼寫處理bit的程式.
其實在C++是使用bitset這個class
bitset的操作行為:
anytrue if any bits are set
countreturns the number of set bits
flipreverses the bitset
nonetrue if no bits are set
resetsets bits to zero
setsets bits
sizenumber of bits that the bitset can hold
testreturns the value of a given bit
to_stringstring representation of the bitset
to_ulongreturns an integer representation of the bitset

範例1 (開啟某個bit):
#include 
#include
using namespace std;

int main ()
{
bitset<4> mybits;

cout << class="comm">// 1111
cout << class="comm">// 1011
cout << class="comm">// 1111

return 0;
}

範例2:
#include
#include
#include
using namespace std;

int main (關閉某個bit)
{
bitset<4> mybits (string("1011"));

cout << class="comm">// 1001
cout << class="comm">// 0000

return 0;
}

沒有留言: