C++ Bitset - C++ Programming Tutorial
C++ Course / STL Set & Map / C++ Bitset

C++ Bitset

BLUF: Mastering C++ Bitset is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Bitset

C++ is renowned for its efficiency. Learn how C++ Bitset enables low-level control and high-performance computing in the tutorial below.

In C++, a bitset represents a collection that stores a predetermined length of binary digits (0s and 1s). This allows for the efficient handling and modification of a fixed-size sequence of bits. The bitset is advantageous for tasks involving low-level operations, compact storage of data, and bitwise operations. It is structured as a template class and declared in the <bitset> header file under the std namespace.

Syntax

It has the following syntax:

Example

std::bitset<N> b;

In this structure, N represents the quantity of bits intended for storage, while b denotes the designated identifier.

Initialization of Bitset

In C++, the bitset function can be initialized in various manners depending on the specific requirements. A bitset represents a sequence of N bits with fixed size, where each bit can be manipulated independently. Upon creation, all bits in a bitset are initially set to 0. Nevertheless, specific values can be assigned to it during declaration. Different ways to initialize a bitset in C++ include:

1) Default Initialization (All Bits = 0)

Example

std::bitset<7> b1;

Here, the bitset is of size 7 bits and

2) Initialization with an Unsigned long

We can also set up a bitset using an unsigned long integer. The binary form of the number is stored in the unsigned long from right to left.

Example

std::bitset<8> b2(42);

3) Initialization using a Binary String

The string should not exceed the size of the bitset or it will be truncated from the left to fit.

Example

std::bitset<8> b3("11001100");

C++ Bitset Example

Let's consider a scenario to demonstrate how we can initialize the bitset in C++.

Example

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:

Output

b1: 00000000

b2: 00001111

b3: 00001111

b4: 10101010

Explanation

In this instance, we showcase the process of initializing std::bitset<8> using various methods. Initially, b1 undergoes default initialization where all bits are set to 0. Following that, b2 is assigned the integer 15, equivalent to the binary representation 00001111. Next, b3 is assigned the binary string "00001111". Finally, b4 is initialized with a std::string containing the bits "10101010".

Accessing Bits

In C++, the std::bitset class enables efficient management and modification of individual bits at any given position. There exist two primary techniques for bit access:

-

  • Test (pos): This method evaluates the bit at the specified position. It returns true (1) if the bit is set to 1, and false (0) if the bit is set to 0.

-

  • operator[pos]: This approach grants direct access to a bit located at a particular position within the bitset.

The pos variable indicates the index or location of the bit starting from 0. It must fall within the specified range of (0 ≤ pos ≤ size - 1); if it exceeds this range, a boundary exception will be triggered.

C++ Accessing Bits Example

Let's consider an example to demonstrate how to retrieve bits in C++.

Example

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:

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 instance, we are working with an 8-bit bitset initialized with the binary value "11001001". Subsequently, we employ the operator along with the test method. These operations ascertain the values of particular bit positions and determine if a bit is set through the test function.

Set, Reset, and Flip Bits

In C++, the std::bitset provides a variety of beneficial functions for manipulating individual or all bits. The set method is employed to assign the bits a value of 1, while the reset function is employed to change bits to 0. Additionally, the flip function can be used to invert the value of a bit - turning a 1 into 0 and a 0 into 1.

C++ Example to Set, Reset, and Flip Bits

Let's consider an instance to demonstrate how we can establish, clear, and toggle bits in C++.

Example

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:

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 instance, we've included the set, reset, and flip methods that operate on single bits as well as the complete bitset. These functionalities enable us to efficiently activate, deactivate, or switch bits within a binary sequence of a predetermined size.

Function in C++ Bitset

There are multiple operations of Bitset in C++. A few of them include:

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 function is employed to verify if all the bits are correctly set.

Syntax

It has the following syntax:

Example

b.all()

It returns true if all bits in the bitset are set to 1; otherwise, it returns false.

C++ bitset::all Example

Let's consider an instance to demonstrate the bitset::all method in C++.

Example

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:

Output

b1.all(): 1

b2.all(): 0

Explanation

In this instance, we showcase the application of the .all method in the std::bitset class. It includes the necessary header files and defines two 8-bit bitsets. The initial bitset, denoted as b1, has all its bits set to 1 (11111111). On the other hand, the second bitset, b2, only has its first four bits set (11110000). When evaluating b1.all, the result is true as all bits are indeed set. Conversely, b2.all yields false as not all bits are set.

bitset::any

In C++, the .any function of std::bitset determines if there is at least a single bit that has a value of 1. If any individual bit within the bitset has a value of 1, the method will result in true. Conversely, in cases where all bits are set to 0, the function will return false.

C++ bitset::any Example

Let's consider a scenario to demonstrate the bitset::any method in C++.

Example

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:

Output

b1.any(): 0

b2.any(): 1

Explanation

In this instance, we are working with two 8-bit bitsets. The first bitset, b1, contains all bits set to 0, while the second bitset, b2, has only one bit set to 1 at the 4th position from the right. Subsequently, the any method is called on both bitsets. When applied to b1, the any method returns false (0) as all bits are 0. Conversely, when applied to b2, the any method returns true (1) as there is at least one bit set to 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's consider a scenario to demonstrate the count and none functions in C++.

Example

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:

Output

b1:       00000000

b1.count(): 0

b1.none():  1

b2:       10101010

b2.count(): 4

b2.none():  0

Explanation

In this instance, the b1.count function provides the count of 1s that are set in b1, which in this case is 0. The b1.none method evaluates to true since there are no bits set to 1 in b1. For b2, the count function returns 4, indicating that there are four 1s in the bitset. Subsequently, b2.none evaluates to false because not all bits are set to 0. Each outcome is then printed to the console for both bitsets. The execution of the program concludes 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's consider an example to demonstrate the operator, size, and test method in the C++ programming language.

Example

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:

Output

Bitset:     10110010

Size:       8

b[2]:       0

b.test(2):  0

Explanation

In this instance, we begin by setting up an 8-bit bitset named b with the binary data "10110010". Next, the bitset is showcased to display its data. The size method is called to fetch the total number of bits in the bitset, which amounts to 8. Following that, b[2] is utilized to access the bit situated at index 2 (counting from the right), yielding a value of 0. Subsequently, b.test(2) is utilized to securely examine the value of the corresponding bit, also returning 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's consider an example to demonstrate the functionality of the tostring, toullong, and to_ulong functions in C++.

Example

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:

Output

Bitset:       10101010

to_string():  10101010

to_ulong():   170

to_ullong():  170

Explanation

In this instance, an 8-bit bitset b is initialized with the binary pattern 10101010. The tostring method is employed to transform the bitset into a string containing '1' and '0', which is then assigned to the variable s. Subsequently, the toulong function changes the bitset into an unsigned long integer, while to_ullong converts it into an unsigned long long integer. Given that 10101010 in binary corresponds to 170 in decimal, both numerical conversions result in 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++, the bitset is employed as a strategy for optimization. It employs a predetermined series of representations of the complete array or vector-based bitset conveyed through true or false, as well as 0 and 1, indicating the clear and set conditions of the bitset representation within a sequence. Consequently, it can be stated that the bitset library in C++ has enhanced and streamlined the operations.

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

The result of b1.count for the given C++ code snippet b1 = std::bitset<8>("10101010") will be the number of set bits in the bitset, which is 4.

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

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience