×

C++ Bitset

Overview

In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true or set. To create bitset of integer or a string bitset class provides constructors. The size of the bitset is determined at compile time.

In other words, bitset is used to fix all the bits to 1. If only one parameter is passed, that bit is assigned at that index.

A bitset is the array of bool. Not every Boolean value needs to be stored separately. Instead, bitset is used to optimize the space for every Boolean value it takes by 1 space or a bit. It must be noted that the space taken by bitset should be less than that or bool[n] and vector[n].

As bitset stores the same information in a compressed manner, the bitset operation is faster than that of array and vector. We can access each bit of bitset individually with the array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array. Remember bitset starts its indexing backward for 10110, 0 are at 0th and 3rd indices whereas 1 is at 1st 2nd and 4th indices.

A bitset follows a compressive manner to store the same operation to execute faster than an array or a vector. They are easily accessible in the array by using an indexing operator[]. However, it is important to note that bitset starts its indexing in reverse direction i.e. backward. For example, 101110 is accounted to be at 0th and 3rd index while 1st and 2nd indices are accounted by 1.

To construct a bitset using integer numbers and binary string, we can do it with constructors by fixing the bitset size at the compile time thus it cannot be changed during runtime.

We can construct a bitset using integer numbers as well as a binary string via constructors which is shown below code. The size of the bitset is fixed at compile time that is, it can't be changed at runtime.

The main functions associated with bitset class are size, reset, set, and many more. Let's visualize this by the coding examples.

Syntax used in the <bitset> header file.

template <size_t N> class bitset;

Example code:

 #include<iostream>
 #include<bitset>
 using namespace std;
 int main ()
 {
   bitset<20> fool(200);
   bitset<20> bark(0xfa2) ;
   bitset<20> buzz (string("0101111001"));
   cout << "fool: " << fool << '\n';
   cout << "bark: " << bark << '\n';
   cout << "buzz: " << buzz << '\n';
   return 0;
 } 

Output:

Explanation:

In the above code, the function bitset is imported from the header file <bitset>. The bitset functions primarily have been passed three arguments like integer, binary address, and a string of numbers. These 3 arguments are of size 2o which can be seen from the output that the integer value prints for 200. The binary value for the bitset bark has been taken as (0xfa2: some value) and the string is defined.

The output corresponding to the inputs is printed up to 20 decimal places for all the arguments.

Let us now look at the different functions associated with the bitset operations with the help of the table of reference below.

Member Types (constructors,functions, operators)Methods and Description
referenceProxy class which is used to represent reference to bit.
       constructorConstructs bitset container and initializes it for int, string etc.
       operatorsPerforms operations like AND, OR, NOT, XOR, left shift, right shift etc.
         all()Tests whether all or atleast one bit are set or not.
        count()Counts number of sets from bitset.
        none()Checks whether bits are unset or not.
        flip()Toggles single or all bitsets.
        set()Sets all bits to 1.
        reset()Sets all bits to 0.
        hash()Return hash value provided by the bitset.
        string()This converts bit objects to string objects.
        test()Checks whether Nth bit is set or not.
        ullong()Coverts bits to long or unsigned long.

Note: There are still plenty of functions present in the bitset library in the C++ language. The above are the most popular and commonly used functions.

Advantages of using bitset:

  1. bitsets are stored in a compressed manner, so the accessing is fast as compared to the arrays or vectors.
  • We can easily use bitset with constructors which make construction easier for data types like integer and binary strings.
  • The bitset size is fixed at compile-time, thus we needn't do it in the runtime which saves time.
  • The bitsets are dynamically adjustable so the array size can increase as needed.  

Related Topics

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.