C++ bitset and its application
Last Updated :
28 Nov, 2024
A bitset is an array of bools but each boolean value is not stored in a separate byte instead, bitset optimizes the space such that each boolean value takes 1-bit space only, so space taken by bitset is less than that of an array of bool or vector of bool.
A limitation of the bitset is that size must be known at compile time i.e. size of the bitset is fixed.
std::bitset is the class template for bitset that is defined inside <bitset> header file so we need to include the header file before using bitset in our program.
Syntax:
bitset<size> variable_name(initialization);
We can initialize bitset in three ways :
1. Uninitialized: All the bits will be set to zero.
bitset<size> variable_name;
2. Initialization with decimal integer: Bitset will represent the given decimal number in binary form.
bitset<size> variable_name(DECIMAL_NUMBER);
3. Initialization with binary string: Bitset will represent the given binary string.
bitset<size> variable_name(string("BINARY_STRING"));
bitset<size> variable_name("BINARY_STRING");
Example:
C++
// C++ program to demonstrate the bitset
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
// declaring an uninitialized bitset object
bitset<8> uninitializedBitset;
// initialization with decimal number
bitset<8> decimalBitset(15);
// initialization with binary string
bitset<8> stringBitset(string("1111"));
cout << "Uninitialized bitset: " << uninitializedBitset
<< endl;
cout << "Initialized with decimal: " << decimalBitset
<< endl;
cout << "Initialized with string: " << stringBitset
<< endl;
return 0;
}
OutputUninitialized bitset: 00000000
Initialized with decimal: 00001111
Initialized with string: 00001111
std::bitset Member Functions
std::bitset class contains some useful member functions to work on the bitset objects. Here is the list of some member functions of std::bitset:
Function Name
| 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 none bit is set. |
all()
| Check if all bit is set. |
size()
| Returns the size of the bitset. |
to_string()
| Converts bitset to std::string. |
to_ulong()
| Converts bitset to unsigned long. |
to_ullong()
| Converts bitset to unsigned long long. |
Example:
C++
// C++ program to demonstrate the
// use of std::bitset member
// functions
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
// declaring index variable
int index = 0;
// declaring few bitset objects
bitset<4> allSet("1111"), allUnset;
cout << "any() value: " << boolalpha << allSet.any()
<< endl;
cout << "all() value: " << allSet.all() << endl;
cout << "none() value: " << allSet.none() << endl;
cout << "test() at index 0: " << noboolalpha
<< allSet.test(index) << endl;
cout << "size() value: " << allSet.size() << endl;
cout << "Value of allUnset on before using set(): "
<< allUnset << endl;
allUnset.set(index);
cout << "Value of allUnset on after using set(): "
<< allUnset << endl;
cout << "Value of allSet on before using reset(): "
<< allSet << endl;
allSet.reset(index);
cout << "Value of allSet on after using reset(): "
<< allSet << endl;
// declaring an empty string
string bitString;
// using to_string() method to assign value to empty
// string
bitString = allSet.to_string();
cout << "bitString: " << bitString << endl;
cout << "Unsigned Long value: " << allSet.to_ulong();
return 0;
}
Outputany() value: true
all() value: true
none() value: false
test() at index 0: 1
size() value: 4
Value of allUnset on before using set(): 0000
Value of allUnset on after using set(): 0001
Value of allSet on before using reset(): 1111
Value of allSet on after using reset(): 1110
bitString: 1110
Unsigned Long value: 14
Note: boolalpha is used to print “true” and “false” instead of 1 or 0 for boolean values and noboolalpha for opposite.
std::bitset Operators
Some of the basic operators are overloaded to work with bitset objects. Following is the list of those operators:
Operator
| Operation
|
|---|
[]
| Access operator |
&
| 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++
// C++ program to show the different operator functions on
// bitset
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
bitset<4> bitset1("1001"), bitset2("1010");
bitset<4> result;
cout << "Bitset1: " << bitset1
<< "\nBitset2: " << bitset2 << endl;
cout << "Accessing bit value at index 1 of bitset1: "
<< bitset1[1] << endl;
// bitwise AND
cout << "Bitwise AND using &: "
<< (result = bitset1 & bitset2) << endl;
cout << "Bitwise AND using &=: " << (bitset1 &= bitset2)
<< endl;
// bitwise OR
bitset1 = 9; // 9 = 1001
cout << "Bitwise OR using |: "
<< (result = bitset1 | bitset2) << endl;
cout << "Bitwise OR using |=: " << (bitset1 |= bitset2)
<< endl;
// bitwise NOT
cout << "Bitwise NOT: " << (result = ~bitset1) << endl;
// bitwise XOR
bitset1 = 9;
cout << "Bitwise XOR: " << (bitset1 ^= bitset2) << endl;
bitset1 = 9;
cout << "Binary leftshift on bitwise1: "
<< (bitset1 <<= 1) << endl;
bitset1 = 9;
cout << "Binary rightshift on bitwise1: "
<< (bitset1 >>= 1) << endl;
return 0;
}
Output
Bitset1: 1001
Bitset2: 1010
Accessing bit value at index 1 of bitset1: 0
Bitwise AND using &: 1000
Bitwise AND using &=: 1000
Bitwise OR using |: 1011
Bitwise OR using |=: 1011
Bitwise NOT: 0100
Bitwise XOR: 0011
Binary leftshift on bitwise1: 0010
Binary rightshift on bitwise1: 0100
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 |
Similar Reads
C++ bitset and its application
A bitset is an array of bools but each boolean value is not stored in a separate byte instead, bitset optimizes the space such that each boolean value takes 1-bit space only, so space taken by bitset is less than that of an array of bool or vector of bool. A limitation of the bitset is that size mus
6 min read
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
Bits manipulation (Important tactics)
Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming Table of Contents Compute XOR from 1 to n (direct method)Count of numbers (x) smaller than or equal to n such that n+x = n^xHow to know if a number is a power of 2?Find XOR of all
15+ min read
Print bitwise AND set of a number N
Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. Examples : Input : N = 5Output : 0, 1, 4, 5 Explanation: 0 &
8 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 bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits Recommended PracticeNumber of 1 BitsTr
15+ min read
Count total set bits in an array
Given an array arr, the task is to count the total number of set bits in all numbers of that array arr. Example: Input: arr[] = {1, 2, 5, 7}Output: 7Explanation: Number of set bits in {1, 2, 5, 7} are {1, 1, 2, 3} respectively Input: arr[] = {0, 4, 9, 8}Output: 4 Approach: Follow the below steps to
5 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
bit_and function in C++
bit_and is a builtin function in C++ which is used to return the values after applying the bitwise_and on its arguments(as returned by operator &). template struct bit_and { T operator() (const T& a, const T& b) const {return a&b;} typedef T type of first_argument; typedef T type of
2 min read
Find position of the only set bit
Given a number N having only one â1â and all other â0âs in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the numb
15+ min read