Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Bits manipulation (Important tactics)
Next article icon

C++ Bitset and its Application

Last Updated : 08 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
bitset<n> name; 

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++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() {      //Driver Code Ends }      // Default Initialization     bitset<5> bnum(18);  //Driver Code Starts{     cout << bnum;     return 0; } //Driver Code Ends } 

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++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() {      //Driver Code Ends }      // Initialize bitset with value     bitset<5> bs2("10010");  //Driver Code Starts{      cout << bs2 << endl;     return 0; }  //Driver Code Ends } 

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++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() {      //Driver Code Ends }      // 18 = (10010)     bitset<5> bs(18);          // Check 3rd bit     cout << bs[2] << endl;          // Check 5th bit     cout << bs.test(4);  //Driver Code Starts{     return 0; } //Driver Code Ends } 

Output
0 1

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++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() { //Driver Code Ends }      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);  //Driver Code Starts{     cout << bs;     return 0; } //Driver Code Ends } 

Output
10011 10001 00001

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++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() { //Driver Code Ends }       // 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);  //Driver Code Starts{     return 0; }  //Driver Code Ends } 

Output
00000 10111 10111

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

  • Find the Size of the Bitset
  • Convert Bitset to Unsigned Long Long
  • Convert Bitset to Unsigned Long
  • Check if at least One Bit is Set in Bitset
  • Check if all Bits are Unset
  • Check if all Bits are Set

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

DefinitionA 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 boolA fixed size contiguous collection of bool data elements.
SizeFixed Size.Dynamic Size.Fixed Size.
MemoryA single element occupies 1 bit of memory.A single element occupies 1 bit of memory.A single element occupies 1 byte of memory.
SpeedSameSameFaster

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.


Next Article
Bits manipulation (Important tactics)

U

Utkarsh Trivedi
Improve
Article Tags :
  • Bit Magic
  • C++
  • DSA
  • CPP-bitset
  • CPP-Library
  • STL
Practice Tags :
  • CPP
  • Bit Magic
  • STL

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
  • 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
  • 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
  • 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 [Naive Approach] - One by One Counting
    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 containing only 1 set bit in its binary representation, the task is to find the position of the only set bit. If there are 0 or more than 1 set bits, then return -1. Note: Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences