![]() |
VOOZH | about |
Bitset is a container that represents a fixed-size sequence of bits. A bitset allows you to manipulate individual bits efficiently, making it useful in problems related to bitwise operations, such as checking flags, implementing binary representations.
Bitset is defined as the std::bitset class template inside the <bitset> header file.
where, n is the number of bits to allocate, and name is the name assigned.
By default, when a bitset of a given size is created, all of its bits are unset i.e. 0. We can initialize it to some value simply by passing it to its constructor.
Here, the bitset bnum is of size 5 bits and stores the decimal value 18 in binary form.
Binary numbers are also represented as strings, so bitset also provide facility to initialize itself from the strings.
The string should represent a valid binary number i.e. all characters should be 0 or 1. Otherwise, an error may occur.
We can access individual bits in a bitset using the [] operator, just like an array.
Example:
0 1
Setting means making the bit at particular position 1 and resetting means making it 0. These operations can be done using set() and reset() function. The flip() function can be used to set the bit if it's not set and unset if it is set.
Example:
10011 10001 00001
Bitset objects can work with all the bitwise operators to provide seamless replacement integration in the code.
Operator | Operation |
|---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
>>= | Binary Right shift and assign |
<<= | Binary Left shift and assign |
&= | Assign the value of bitwise AND to the first bitset. |
|= | Assign the value of bitwise OR to the first bitset. |
^= | Assign the value of bitwise XOR to the first bitset. |
~ | Bitwise NOT |
Example:
00000 10111 10111
Vector of bool and array of bool can also be implemented to store a sequence of boolean values like bitset but there are some differences between each implementation:
| Parameter | bitset | vector of bool | array of bool |
|---|---|---|---|
| Definition | A class template consisting of a sequence of bits stored such that each bit occupies 1 bit of memory. | A variation of vectors of C++ STL in which each element is of size 1 bit and is of type bool | A fixed size contiguous collection of bool data elements. |
| Size | Fixed Size. | Dynamic Size. | Fixed Size. |
| Memory | A single element occupies 1 bit of memory. | A single element occupies 1 bit of memory. | A single element occupies 1 byte of memory. |
| Speed | Same | Same | Faster |