A set of individual flags is often most efficiently stored as a sequence of bits. std::bitset provides a fixed length sequence of bits with an easy to use API for setting, testing and converting to other formats.
The size of a bitset is a constant determined during compile time that is passed as a template argument. When a bitset is initialized using the default constructor all bits are set to zero.
#include <iostream>
#include <bitset>
int main()
{
// Store a fixed number of bits in this bitset
std::bitset<8> b;
std::cout << b << '\n';
}
There are 8 bits in object b, and they are all initially zero. Streaming b to std::cout causes the bit pattern 00000000 to be printed. The bit furthest to the left has the largest number.
bitset can be defined from an integer value. Bits of that number will be the initial contents of bitset.
#include <iostream>
#include <bitset>
int main()
{
// Use binary notation for this integer literal
std::bitset<8> b{ 0b10101010 };
std::cout << b << '\n';
}
The value 0b10101010, an integer literal, gives the initial pattern. The bitset b must therefore contain precisely those eight bits, and output of b is 10101010.
Individual bits are inspected and manipulated by member functions or by the subscript operator. The following program sets one bit, tests the value of another, and flips a third.
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b;
// Call the setter to update the object state
b.set(3);
b.flip(0);
std::cout << b.test(3) << ' ' << b[0] << ' ' << b << '\n';
}
The call b.set(3) turns bit 3 on. The call b.flip(0) turns bit 0 off. b.test(3) returns true as that bit is now on and b[0] returns true as the flip turned it on. The final insertion will now output the entire pattern 00001001.
A bitset can be built from a string of '0' and '1' characters also.
#include <iostream>
#include <bitset>
int main()
{
std::bitset<6> b{ "110010" };
std::cout << b.to_ulong() << '\n';
}
The string "110010" supplies the six bits. The member function to_ulong() converts the bit pattern into an unsigned long which is then printed. The value is 50 because the binary 110010 is equivalent to fifty.
The size of a bitset is determined at compile time. A bitset cannot dynamically grow or shrink. If the number of bits that need to be handled is known beforehand and is small, a bitset can be a clearer and safer approach than directly using unsigned integers with shifting and masking.
0 comments
No comments yet. Be the first.