1、构造函数
(1)bitset ( );//空的,默认设置为0
(2)bitset ( unsigned long val ); //参数可以使字符串,
使用
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
int main ()
{
bitset<10> first; // empty bitset
bitset<10> second (120ul); // initialize from unsigned long
bitset<10> third (string("01011")); // initialize from string
cout << first << endl; // 00000 00000
cout << second << endl; // 00011 11000(120的二进制表示)
cout << third << endl; // 00000 01011
return 0;
}
2、bit access:operator[]
bool operator[] ( size_t pos ) const;
reference operator[] ( size_t pos );
使用
bitset<4> mybits;
mybits[1]=1; // 0010
mybits[2]=mybits[1]; // 0110
cout << "mybits: " << mybits << endl
3、Bit operations:
bit::set
bitset<N>& set ( ); //全部设置为1
bitset<N>& set ( size_t pos, bool val = true );
bit::reset
bitset<N>& reset ( ); //全部设置为0,复位
bitset<N>& reset ( size_t pos ); //指定位置设为0
bitset::flip 取反
changes all 0s for 1s and all 1s for 0s.
改变所有的0位1,改变所有的1位0。
bitset<N>& flip ( ); //全部取反
bitset<N>& flip ( size_t pos );//指定位置取反
4、Bitset operations:
(1) bitset::to_ulong
将位图转换为unsigned long
bitset<4> mybits; // mybits: 0000
mybits.set(); // mybits: 1111
mybits.to_ulong(); // 15
(2)bitset::to_string
将位图转化为string
string mystring;
bitset<4> mybits; // mybits: 0000
mybits.set(); // mybits: 1111
mystring=mybits.to_string<char,char_traits<char>,allocator<char> >();
cout << "mystring: " << mystring << endl; //1111
(3)bitset::count
bitset<8> myset (string("10110011"));
cout << "myset has " << int(myset.count()) << " ones ";
cout << "and " << int(myset.size()-myset.count()) << " zeros.\n";
// myset has 5 ones and 3 zeros
(4)bitset::size
size_t size() const;
//Return size
//Returns the number of bits in the bitset.
(5)bitset::test
判断某个位置是否被设置为true,
注:位图是从右边起始位置为0的位置
bitset<5> mybits (string("01011"));
cout << "mybits contains:\n";
for (size_t i=0; i<mybits.size(); ++i)
cout << mybits.test(i) << endl;
输出:
mybits contains:
true
true
false
true
false
(6)bitset::any
测试所有的bit位是否被设置
bool any ( ) const;
//Test if any bit is set
//Returns whether any of the bits in the bitset is set.
(7)bitset::none
测试是否所有bit位没有被设置
bool none ( ) const;
//Test if no bit is set
//Returns whether none of the bits in the bitset are set.
参考:https://blog.csdn.net/wenqiang1208/article/details/76739120