In C++, a bitset is a container that holds a fixed-size sequence of bits (0s and 1s). It enables us to manage and manipulate a fixed-size sequence of bits efficiently. It is useful for low-level operations, memory-efficient storage, and bitwise logic. It is implemented as a class template and defined in the <bitset> header file within the std namespace .
Syntax
It has the following syntax:
std::bitset<N> b;
In this syntax, N is the number of bits that we want to store, and b is the name that is assigned.
Initialization of Bitset
In C++ , we can initialize the bitset function in several ways based on their use cases. A bitset is a fixed-size sequence of N bits (such as 0's and 1's), where we can manipulate each bit individually. When we create a bitset, all bits are unset (0) by default. However, we may initialize it with definite values during its declaration. Several initializations of bitset in C++ are as follows:
1) Default Initialization (All Bits = 0)
std::bitset<7> b1;
Here, the bitset is of size 7 bits and
2) Initialization with an Unsigned long
We can also initialize a bitset with an unsigned long value. In the unsigned long, the binary representation of the number is stored from right to left.
std::bitset<8> b2(42);
3) Initialization using a Binary String
The string must have the same or fewer characters than the size of the bitset. Extra bits are truncated from the left.
std::bitset<8> b3("11001100");
C++ Bitset Example
Let us take an example to illustrate how we can initialize the bitset in C++.
Example
#include <iostream>
#include <bitset>
int main() { //Main Function
std::bitset<8> b1;
std::bitset<8> b2(15);
std::bitset<8> b3("00001111");
std::bitset<8> b4(std::string("10101010"));
std::cout << "b1: " << b1 << std::endl;
std::cout << "b2: " << b2 << std::endl;
std::cout << "b3: " << b3 << std::endl;
std::cout << "b4: " << b4 << std::endl;
return 0;
}
Output:
b1: 00000000
b2: 00001111
b3: 00001111
b4: 10101010
Explanation
In this example, we demonstrate how to initialize std::bitset<8> in different ways. First, b1 is default-initialized (all bits 0). b2 employs the integer 15, which is represented in binary as 00001111. b3 employs a binary string "00001111". b4 is utilizing a std::string with bits "10101010".
Accessing Bits
In C++, the std::bitset container allows efficient access and manipulation of individual bits at any position. There are two main methods to access bits.
- Test (pos): If the bit at the position is 1, it returns true (1), and if the bit at the position is 0, it returns false (0).
- operator[pos]: It provides direct access to a bit at a specific position.
The pos represents the index or position of the bit from 0. It should be in the range (0 ≤ pos ≤ size - 1); otherwise, a bound exception is raised.
C++ Accessing Bits Example
Let us take an example to illustrate how to access bits in C++.
Example
#include <iostream>
#include <bitset>
using namespace std; //using standard namespace
int main() { //Main Function
bitset<8> bits("11001001"); //Definiing bits
cout << "Bitset: " << bits << endl;
//Accessing individual bits using the [] operator
cout << "Bit at position 0: " << bits[0] << endl;
cout << "Bit at position 5: " << bits[5] << endl;
// Using the test() function
if (bits.test(4)) {
cout << "Bit at position 4 is set (1)." << endl;
} else {
cout << "Bit at position 4 is not set (0)." << endl;
}
bits[3] = 0; // Unset bit
bits[6] = 1; // Set bit
cout << "Modified Bitset: " << bits << endl;
return 0;
}
Output:
Bitset: 11001001
Bit at position 0: 1
Bit at position 5: 0
Bit at position 4 is not set (0).
Modified Bitset: 11000001
Explanation
In this example, we have taken a bitset of 8 bits that is initialized with the binary value "11001001". After that, we use the operator and the test function. These functions check specific bit positions and print their values, while the test function is used to check if a bit is set.
Set, Reset, and Flip Bits
In C++, the std::bitset offers many useful functions to work individual or all bits. We can use the set function to set the bits to 1, and use the reset function to clear bits by setting the bit to 0. After that, the flip function can also be utilized to toggles the bit's value. If the bit is 1, it becomes 0, and if it is 0, it becomes 1.
C++ Example to Set, Reset, and Flip Bits
Let us take an example to illustrate how we can set, reset, and flip bits in C++.
Example
#include <iostream>
#include <bitset>
int main() { //Main Function
std::bitset<8> b("00001100");
std::cout << "Original: " << b << std::endl;
b.set(0); //using set() function
std::cout << "After set(0): " << b << std::endl;
b.set();
std::cout << "After set(): " << b << std::endl;
b.reset(3); //using reset() function
std::cout << "After reset(3):" << b << std::endl;
b.reset();
std::cout << "After reset(): " << b << std::endl;
b.flip(1); //using flip() function
std::cout << "After flip(1): " << b << std::endl;
b.flip();
std::cout << "After flip(): " << b << std::endl;
return 0;
}
Output:
Original: 00001100
After set(0): 00001101
After set(): 11111111
After reset(3):11110111
After reset(): 00000000
After flip(1): 00000010
After flip(): 11111101
Explanation
In this example, we have taken the set, reset, and flip functions that work on individual bits and the entire bitset. These operations allow us to turn bits on and off or toggle them efficiently in a fixed-size binary sequence.
Function in C++ Bitset
There are several functions of Bitset in C++. Some of them are as follows:
| Function | Description |
|---|---|
| all() | It is used to test and check whether all the bits are set. |
| any() | It is used to check if any bit is set. |
| count() | It is used to count the number of set bits. |
| flip() | It is used to flip the bit value at the provided index. |
| none() | It is used to check if all bits are unset. |
| operator[] | It is used to enable access to individual bits by index. |
| reset() | It is used to set the value of bit at a given index to 0. |
| set() | It is used to set the value of bit at a given index to 1. |
| size() | It is used to return the size of bitset. |
| test() | It is used to return the Boolean value at a given index. |
| to_string() | It is used to convert the bitset to string. |
| to_ullong() | It is used to convert the bitset to unsigned long long. |
| to_ulong()() | It is used to convert the bitset to unsigned long. |
Now, we will discuss these functions one by one.
bitset::all
In C++ bitsets, this operation is utilized for testing and checking whether all the bits are set appropriately.
Syntax
It has the following syntax:
b.all()
It returns true if every bit in the bitset is 1; otherwise false.
C++ bitset::all Example
Let us take an example to illustrate the bitset::all function in C++.
Example
#include <iostream>
#include <bitset>
int main() { //Main Function
std::bitset<8> b1("11111111");
std::bitset<8> b2("11110000");
std::cout << "b1.all(): " << b1.all() << std::endl;
std::cout << "b2.all(): " << b2.all() << std::endl;
return 0;
}
Output:
b1.all(): 1
b2.all(): 0
Explanation
In this example, we demonstrate the .all member function in std::bitset. It consists of the appropriate headers and declares two 8-bit bitsets. The initial bitset b1 has all its bits set to 1 (11111111). The second bitset, b2, has only its first four bits set (11110000). The b1.all function returns true since all bits are set, but b2.all returns false because not all bits are set.
bitset::any
In C++, the .any method of std::bitset returns whether at least one bit is equal to 1.
- If any one bit of the bitset is 1, it returns true.
- If all the bits are 0, it returns false.
C++ bitset::any Example
Let us take an example to illustrate the bitset::any function in C++.
Example
#include <iostream>
#include <bitset>
int main() { //main function
std::bitset<8> b1("00000000");
std::bitset<8> b2("00010000");
std::cout << "b1.any(): " << b1.any() << std::endl;
std::cout << "b2.any(): " << b2.any() << std::endl;
return 0;
}
Output:
b1.any(): 0
b2.any(): 1
Explanation
In this example, we have taken two 8-bit bitsets, b1 with all the bits as 0 and b2 with a single bit set as 1 at position 4 from the right side. After that, the any method is invoked on both the bitsets. For b1, any function gives false (0) since all bits are 0. For b2, any gives true (1) because it has at least one bit as 1.
bitset::count and bitset::none
- In C++, the count method returns the number of bits set to 1 in the bitset.
- The none is true whenever all the bits are 0; otherwise false.
C++ bitset::count and none Example
Let us take an example to illustrate the count and none functions in C++.
Example
#include <iostream>
#include <bitset>
int main() { //Main Function
std::bitset<8> b1("00000000");
std::bitset<8> b2("10101010");
std::cout << "b1: " << b1 << std::endl;
std::cout << "b1.count(): " << b1.count() << std::endl;
std::cout << "b1.none(): " << b1.none() << std::endl;
std::cout << "b2: " << b2 << std::endl;
std::cout << "b2.count(): " << b2.count() << std::endl;
std::cout << "b2.none(): " << b2.none() << std::endl;
return 0;
}
Output:
b1: 00000000
b1.count(): 0
b1.none(): 1
b2: 10101010
b2.count(): 4
b2.none(): 0
Explanation
In this example, the expression b1.count gives the number of 1s set in b1, which is 0. b1.none returns true as there are no bits set to 1 in b1. For b2, count gives 4, as there are four 1s in the bitset. After that, b2.none returns false as not all bits are set to 0. Each result is displayed to the console for both bitsets. The program terminates by returning 0.
bitset::operator, bitset::size and bitset::test
- In C++ bitset, the operator function is used to refer to specific bits.
- The size function is used to return the number of bits.
- The test function is used to access the value of a bit at a given position.
C++ bitset::operator, size, and test Example
Let us take an example to illustrate the operator, size, and test function in C++.
Example
#include <iostream>
#include <bitset>
int main() { //Main Function
std::bitset<8> b("10110010");
std::cout << "Bitset: " << b << std::endl;
std::cout << "Size: " << b.size() << std::endl;
std::cout << "b[2]: " << b[2] << std::endl;
std::cout << "b.test(2): " << b.test(2) << std::endl;
return 0;
}
Output:
Bitset: 10110010
Size: 8
b[2]: 0
b.test(2): 0
Explanation
In this example, we start by initializing an 8-bit bitset b with the binary value "10110010". After that, the bitset is displayed to reveal its contents. The size member function is invoked to retrieve the number of bits in the bitset, which is 8. Subsequently, b[2] is employed to refer to the bit at position 2 (from the right), and it returns 0. After that, b.test(2) is employed to check the value of the same bit safely, and it returns 0.
bitset::to_string, bitset::to_ullong, and bitset::to_ulong
- In C++ bitset, the to_string function returns a string representation of the bitset containing '0' and '1' characters.
- The to_ullong function returns an unsigned long long integer representing the bitset.
- The to_ulong function returns an unsigned long integer representing the bitset.
C++ to_string, to_ullong, and to_ulong Example
Let us take an example to illustrate the tostring, toullong, and to_ulong function in C++.
Example
#include <iostream>
#include <bitset>
#include <string>
int main() { //Main Function
std::bitset<8> b("10101010");
std::string s = b.to_string();
unsigned long ul = b.to_ulong();
unsigned long long ull = b.to_ullong();
std::cout << "Bitset: " << b << std::endl;
std::cout << "to_string(): " << s << std::endl;
std::cout << "to_ulong(): " << ul << std::endl;
std::cout << "to_ullong(): " << ull << std::endl;
return 0;
}
Output:
Bitset: 10101010
to_string(): 10101010
to_ulong(): 170
to_ullong(): 170
Explanation
In this example, an 8-bit bitset b is created with the binary value 10101010. The tostring function is used to convert the bitset to a string of characters '1' and '0', which is stored in the variable s. After that, the toulong operation converts the bitset to an unsigned long integer, and to_ullong converts it to an unsigned long long integer. As 10101010 in binary is the same as 170 in decimal, both numeric conversions yield the value 170.
Why Bitset is the Better Choice
In C++, bitsets are a class of choice to perform bitwise operations and manipulate binary data because of the following:
- Bitsets are economical in memory because each bit needs only one bit, which is why they are suitable for big binary datasets.
- Bitsets allow low-cost bit manipulations with improved alternatives over using integers or boolean arrays to handle big-bit arrays.
- The Bitset offers a convenient means of working with bits without the need to write complex custom functions.
- Because the size of a bitset is known at compile time, it facilitates uniform memory usage and performance and is thus particularly suitable for use in applications where efficiency matters.
- The use of bitsets unambiguously indicates bit-level manipulation, which enhances code readability and minimizes errors.
Conclusion
In C++, bitset is utilized as an optimization technique. It uses a fixed set of representations of the whole array or vector-based bitset expressed in terms of true or false and 0 and 1, which signifies the unset and set state of the bitset representation in a stream. Hence, it can be said that the bitset C++ standard library has improved and simplified the processes.
C++ Bitset MCQs
1) What does the std::bitset<8> b1; statement do in C++?
- Initializes all bits to 1
- Initializes all bits to 0
- Leaves bits uninitialized
- Initializes from a default binary string
2) Which of the following bitset functions returns true if at least one bit is set in C++?
- all
- none
- any
- test
3) What will the output of b1.count if b1 = std::bitset<8>("10101010") in C++?
4) Which function flips all bits in a bitset in C++?
- flip(pos)
- flip
- reset
- set
5) Which of the following methods throws an exception if the index is out of range in C++?
- operator
- test
- count
- size