bitsetを使う

STLのbitsetの使い方がいまいちよくわからなかったので、動作確認も含めてまとめる。

#include <bitset>
#include <iostream>
using namespace std;

int main()
{
	// initialize 8bit bitset as 1
	bitset<8> bs((long) 1);
	cout << "original : " << bs << endl;
	//make all bit 1
	bs.set();
	cout << "set : " << bs << endl;
	//change first bit to 0(false)
	bs[0]=0;
	cout << "bs[0]=0 : " << bs << endl;
	//third bit is setted to 0(false)
	bs.set(2,0);
	cout << "set(2,0) : " << bs << endl;
	//flip all bits
	bs.flip();
	cout << "flip : " << bs << endl;
	//flip second bit
	bs.flip(2);
	cout << "flip(2) : " << bs << endl;
	//shift
	bs <<= 1;
	cout << "<<=1 : " << bs << endl;
	//convert other types
	cout << "to_string : " << bs.to_string() << endl;
	cout << "to_ulong : " << bs.to_ulong() << endl;
	//count the number of being setted as 1
	cout << "count : " << bs.count() << endl;
	//bitsize(8)
	cout << "size : " << bs.size() << endl;
	
	cout << "increment" << endl;
	//increment bit
	for(int i = 0;i < 10;i++)
	{
		bitset<8> x(i);
		cout << x << endl;
	}
	return 0;
}

出力結果

original : 00000001
set : 11111111
bs[0]=0 : 11111110
set(2,0) : 11111010
flip : 00000101
flip(2) : 00000001
<<=1 : 00000010
to_string : 00000010
to_ulong : 2
count : 1
size : 8
increment
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00001000
00001001