In computing, a flag is a value that signals when some condition exists in a program. With a bit flag, a value of true means the condition exists.
<bitset> // for std::bitset
std:: bitset<8> mybitset {}; // 8 bits in size means room for 8 flags.
std::bitset not only print values in binary, it can also...
Each of these functions takes the position of the bit we want to operate on as their only argument.
#include <bitset>
#include <iostream>
using namespace std;
int main() {
bitset<8> bits { 0b000'0101 }; // we need 8 bits, start with bit pattern 0000 0101
cout << "Start: " << bits << '\n';
cout << "bits.set(3): " << bits.set(3) << '\n';
cout << "bits.flip(4): " << bits.flip(4) << '\n';
cout << "bits.reset(4): " << bits.reset(4) << '\n'; // sets bit 4 back to 0
cout << "bit 3 has value of: " << bits.test(3) << '\n';
cout << "bitset indexing goes from right to left.";
return 0;
}
Output:
Start: 00000101
bits.set(3): 00001101
bits.flip(4): 00011101
bits.reset(4): 00001101
bit 3 has value of: 1
bitset indexing goes from right to left.
bitset<8> bits { 0b000'1101 };
cout << bits.size() << " bits are in the bitset\n";
cout << bits.count() << " bits are set to true\n";
cout << boolalpha; // changes how boolean values are printed to the console.
cout << "All bits are true: " << bits.all() << '\n';
cout << "Some bits are true: " << bits.any() << '\n';
cout << "No bits are true: " << bits.none() << '\n';
Output:
8 bits are in the bitset
3 bits are set to true
All bits are true: false
Some bits are true: true
No bits are true: false