A bitset provides the most commonly used bitwise operations in an efficient form. However, each bitset is implemented by logically packing bits in an array of integral types (typically unsigned longs, which contain at least 32 bits). In addition, the only conversion from a bitset to a numerical value is to an unsigned long (via the function to_ulong( )).
The following example tests almost all the functionality of the bitset (the missing operations are redundant or trivial). You’ll see the description of each of the bitset outputs to the right of the output so that the bits all line up, and you can compare them to the source values. If you still don’t understand bitwise operations, running this program should help.
//: C07:BitSet.cpp
//{-bor}
// Exercising the bitset class
#include
#include
#include
#include
#include
#include
using namespace std;
const int sz = 32;
typedef bitset
template
bitset
bitset
for(int i = 0; i < bits/16 - 1; i++) {
r <<= 16;
// "OR" together with a new lower 16 bits:
r |= bitset
}
return r;
}
int main() {
srand(time(0));
cout << "sizeof(bitset<16>) = "
<< sizeof(bitset<16>) << endl;
cout << "sizeof(bitset<32>) = "
<< sizeof(bitset<32>) << endl;
cout << "sizeof(bitset<48>) = "
<< sizeof(bitset<48>) << endl;
cout << "sizeof(bitset<64>) = "
<< sizeof(bitset<64>) << endl;
cout << "sizeof(bitset<65>) = "
<< sizeof(bitset<65>) << endl;
BS a(randBitset
// Converting from a bitset:
unsigned long ul = a.to_ulong();
cout << a << endl;
// Converting a string to a bitset:
string cbits("111011010110111");