C++ Bitset and its Application
Last Updated :
21 May, 2025
In C++, the 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.
Creating a Bitset
The syntax to create bitset is as follows:
C++
where, n is the number of bits to allocate, and name is the name assigned.
Initializing
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Default Initialization
bitset<5> bnum(18);
cout << bnum;
return 0;
}
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// Initialize bitset with value
bitset<5> bs2("10010");
cout << bs2 << endl;
return 0;
}
The string should represent a valid binary number i.e. all characters should be 0 or 1. Otherwise, an error may occur.
Accessing Individual Bits
We access the bit at any position by using below methods:
- test(pos): Returns 1 if the bit at position is 1, and 0 if it is 0.
- operator[pos]: Allows direct access to a bit at a given position.
Here, pos is the position or index of the bit starting from 0. It must be in the range (0 ≤ pos ≤ size – 1), otherwise, out of bound exception is thrown.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// 18 = (10010)
bitset<5> bs(18);
// Check 3rd bit
cout << bs[2] << endl;
// Check 5th bit
cout << bs.test(4);
return 0;
}
Setting, Resetting and Flipping
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:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
bitset<5> bs(18);
// Set 1st bit
bs.set(0);
cout << bs << endl;
// Reset 2nd bit
bs.reset(1);
cout << bs << endl;
// Flip 5th bit
bs.flip(4);
cout << bs;
return 0;
}
Bitset Operators
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:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
// 18 = (10010)
bitset<5> bs1(18);
// 5 = (00101)
bitset<5> bs2(5);
// AND Operator
cout << (bs1 & bs2) << endl;
// OR Operator
cout << (bs1 | bs2) << endl;
// XOR operator
cout << (bs1 ^ bs2);
return 0;
}
Explanation: In the above example, we perform AND, OR and XOR operator on bitsets:
- bs1 & bs2: Return (0 0 0 0).
- bs1 | bs2: Print (1 0 1 1 1).
- bs1 ^ bs2: Print (1 0 1 1 1).
Other Basic Operations
Internal Working
In C++, bitset is implemented using an array or similar structure to store its bits. When you perform operations like set(), reset(), or flip(), they directly modify the bits in the internal array. The size of the bitset is fixed at compile-time, and it cannot be dynamically resized.
Why Bitset is Preferred
Bitsets are a preferred choice for bitwise operations and binary data handling due to the following reasons:
- Bitsets are memory-efficient, as each bit occupies just one bit, making them ideal for large binary datasets.
- Bitsets enable efficient bit manipulation, providing a better alternative to integers or arrays of booleans for handling large bit sequences.
- The bitset provides an easy way to work with bits, eliminating the need for writing complicated custom functions.
- Since the size of a bitset is determined at compile time, it helps with consistent memory usage and performance, making it well-suited for applications where efficiency is important.
- Using bitsets clearly signals bit-level manipulation, which improves code clarity and reduces errors.
Difference between std::bitset and std::vector<bool> and an array of bool
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 |
All Member Functions
Here’s the list of all member functions of std::bitset:
Function | Description |
---|
set() | Set the bit value at the given index to 1. |
---|
reset() | Set the bit value at a given index to 0. |
---|
flip() | Flip the bit value at the given index. |
---|
count() | Count the number of set bits. |
---|
test() | Returns the boolean value at the given index. |
---|
any() | Checks if any bit is set. |
---|
none() | Checks if all bits are unset. |
---|
all() | Check if all bit is set. |
---|
size() | Returns the size of the bitset. |
---|
to_string() | Converts bitset to string. |
---|
to_ulong() | Converts bitset to unsigned long. |
---|
to_ullong() | Converts bitset to unsigned long long. |
---|
Similar Reads
bitset any() in C++ STL The bitset::any() is an inbuilt function in C++ STL which returns True if at least one bit is set in a number. It returns False if all the bits are not set or if the number is zero. Syntax: bool any() Parameter: The function does not accepts any parameter. Return Value: The function returns a boolea
2 min read
showbits( ) Function in C with Examples Bitwise operators are operators (just like +, *, &&, etc.) that operate on ints and units at the binary level. This means they look directly at the binary digits or bits of an integer. This all sounds scary, but in truth, bitwise operators are quite easy to use and also quite useful! It is i
4 min read
bitset all() function in C++ STL The bitset::all() is a built-in function in C++ STL which returns True if all bits are set in the binary representation of a number if it is initialized in the bitset. It returns False if all the bits are not set. Syntax: bool bitset_name.all() Parameter: This function does not accepts any parameter
2 min read
Count set bits in an integer Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits[Naive Approach] - One by One CountingTh
15+ min read
Arithmetic operations with std::bitset in C++ A bitset is an array of boolean values, but each boolean value is not stored separately. Instead, bitset optimizes the space such that each bool takes 1-bit space only, so space taken by bitset say, bs is less than that of bool bs[N] and vector<bool> bs(N). However, a limitation of bitset is,
3 min read