1.bitset基本用法:
#include <iostream>
#include <bitset>
using namespace std;
int main ()
{
bitset<16> mybits;
cout << "enter a binary number: ";
cin >> mybits;
if (mybits.any())
cout << "mybits has " << (int)mybits.count() << " bits set./n";
else cout << "mybits has no bits set./n";
return 0;
}
2.count用法
size_t count ( ); //返回mybits中1的个数
3.flip用法
bitset<N>& flip ( ); //返回mybits的反码
bitset<N>& flip ( size_t pos ); //将从右边数第pos个元素取反码
样例代码:
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <bitset>
#define Elem int
using namespace std;
int main()
{
bitset<10> mybits(string("1010101000"));
cout<<mybits.flip(2)<<endl;
cout<<mybits.flip()<<endl;
return 0;
}
4.none的用法:
bool none ( ) const;
注: 如果mybits中没有1,返回ture;如果mybits中有1,返回false.
5.[]用法:
样例代码:
#include <iostream>
#include <bitset>
using namespace std;
int main ()
{
bitset<4> mybits;
mybits[1]=1; // 0010
mybits[2]=mybits[1]; // 0110
cout << "mybits: " << mybits << endl;
return 0;
}
6.reset用法
bitset<N>& reset ( ); //将mybits中的所有位置0
bitset<N>& reset ( size_t pos ); //将从右数索引为pos的位置0
7.set用法
bitset<N>& set ( ); //将mybits的所有位置1
bitset<N>& set ( size_t pos, bool val = true );//将从右数索引为pos的位置val(1或0)
8.size用法
size_t size() const; //返回mybits的位数
9.test用法
bool test ( size_t pos ) const;//如果从右数索引为pos的位置为1,返回true,否则返回false
10.to_string和to_ulong的用法
注:将二进制数转化为string型或usigned long型
样例代码(to_string):
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <bitset>
#define Elem int
using namespace std;
int main()
{
string mystring;
bitset<4> mybits; // mybits: 0000
mybits.set(); // mybits: 1111
mystring=mybits.to_string();
cout << "mystring: " << mystring << endl;
return 0;
}
样例代码(to_ulong):
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <bitset>
#define Elem int
using namespace std;
int main()
{
bitset<4> mybits; // mybits: 0000
mybits.set(); // mybits: 1111
cout << mybits<<"as an integer is: " << mybits.to_ulong()<< endl;
return 0;
}