To construct an std::bitset object, use one of the available constructors:
- An empty bitset with all bits set to 0:
std::bitset<8> b1; // [0,0,0,0,0,0,0,0]
- A bitset from a numerical value:
std::bitset<8> b2{ 10 }; // [0,0,0,0,1,0,1,0]
- A bitset from a string of '0' and '1':
std::bitset<8> b3{ "1010"s }; // [0,0,0,0,1,0,1,0]
- A bitset from a string containing any two characters representing '0' and '1'; in this case, we must specify which character represents a 0 and which character represents a 1:
std::bitset<8> b4
{ "ooooxoxo"s, 0, std::string::npos, 'o', 'x' };
// [0,0,0,0,1,0,1,0]
To test individual bits in the set or the entire set for specific values, use any of the available methods:
- count() to get the number of bits set to 1:
std::bitset<8> bs{ 10 };
std::cout << "has " << bs.count() << " 1s" << std::endl;
- any() to check whether there is at least one bit set to 1:
if (bs.any()) std::cout << "has some 1s" << std::endl;
- all() to check whether all the bits are set to 1:
if (bs.all()) std::cout << "has only 1s" << std::endl;
- none() to check whether all the bits are set to 0:
if (bs.none()) std::cout << "has no 1s" << std::endl;
- test() to check the value of an individual bit:
if (!bs.test(0)) std::cout << "even" << std::endl;
- operator[] to access and test individual bits:
if(!bs[0]) std::cout << "even" << std::endl;
To modify the content of a bitset, use any of the following methods:
- Member operators |=, &=, ^= , and ~ to perform binary or, and, xor, and not operations, or non-member operators |, &, and ^:
std::bitset<8> b1{ 42 }; // [0,0,1,0,1,0,1,0]
std::bitset<8> b2{ 11 }; // [0,0,0,0,1,0,1,1]
auto b3 = b1 | b2; // [0,0,1,0,1,0,1,1]
auto b4 = b1 & b2; // [0,0,0,0,1,0,1,0]
auto b5 = b1 ^ b2; // [1,1,0,1,1,1,1,0]
auto b6 = ~b1; // [1,1,0,1,0,1,0,1]
- Member operators <<=, <<, >>=, >> to perform shifting operations:
auto b7 = b1 << 2; // [1,0,1,0,1,0,0,0]
auto b8 = b1 >> 2; // [0,0,0,0,1,0,1,0]
- flip() to toggle the entire set or an individual bit from 0 to 1 or from 1 to 0:
b1.flip(); // [1,1,0,1,0,1,0,1]
b1.flip(0); // [1,1,0,1,0,1,0,0]
- set() to change the entire set or an individual bit to true or the specified value:
b1.set(0, true); // [1,1,0,1,0,1,0,1]
b1.set(0, false); // [1,1,0,1,0,1,0,0]
- reset() to change the entire set or an individual bit to false:
b1.reset(2); // [1,1,0,1,0,0,0,0]
To convert a bitset to a numerical or string value, use the following methods:
- to_ulong() and to_ullong() to convert to unsigned long or unsigned long long:
std::bitset<8> bs{ 42 };
auto n1 = bs.to_ulong(); // n1 = 42UL
auto n2 = bs.to_ullong(); // n2 = 42ULL
- to_string() to convert to std::basic_string; by default the result is a string containing '0' and '1', but you can specify a different character for these two values:
auto s1 = bs.to_string(); // s1 = "00101010"
auto s2 = bs.to_string('o', 'x'), // s2 = "ooxoxoxo"