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
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Subtract two numbers without using arithmetic operators
Next article icon

Arithmetic operations with std::bitset in C++

Last Updated : 17 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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, N must be known at compile-time, i.e., a constant (this limitation is not there with vector and dynamic array)

Important Note:

  • Take care of integer overflow say if bitset is declared of size 3 and addition results 9, this is the case of integer overflow because 9 cannot be stored in 3 bits.
  • Take care for negative results as bitsets are converted to unsigned long integer, so negative numbers cannot be stored.

Addition of 2 bitsets: Follow the steps below to solve the problem:

  • Initialize a bool carry to false.
  • Create a bitset ans to store the sum of the two bitsets x and y.
  • Traverse the length of the bitsets x and y and use the fullAdder function to determine the value of the current bit in ans.
  • Return ans.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Utility function to add two bool values and calculate // carry and sum bool fullAdder(bool b1, bool b2, bool& carry) {     bool sum = (b1 ^ b2) ^ carry;     carry = (b1 && b2) || (b1 && carry) || (b2 && carry);     return sum; } // Function to add two bitsets bitset<33> bitsetAdd(bitset<32>& x, bitset<32>& y) {     bool carry = false;     // bitset to store the sum of the two bitsets     bitset<33> ans;     for (int i = 0; i < 33; i++) {         ans[i] = fullAdder(x[i], y[i], carry);     }     return ans; } // Driver Code int main() {     // Given Input     bitset<32> a(25);     bitset<32> b(15);      // Store the result of addition     bitset<33> result = bitsetAdd(a, b);      cout << result;     return 0; } 

Output
000000000000000000000000000101000

Time Complexity: O(N), N is length of bitset
Auxiliary Space: O(N)

Subtraction of 2 bitsets: Follow the steps below to solve the problem:

  • Initialize a bool borrow to false.
  • Create a bitset ans to store the difference between the two bitsets x and y.
  • Traverse the length of the bitsets x and y and use the fullSubtractor function to determine the value of the current bit in ans.
  • Return ans.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Utility function to subtract two bools and calculate diff // and borrow bool fullSubtractor(bool b1, bool b2, bool& borrow) {     bool diff;     if (borrow) {         diff = !(b1 ^ b2);         borrow = !b1 || (b1 && b2);     }     else {         diff = b1 ^ b2;         borrow = !b1 && b2;     }     return diff; } // Function to calculate difference between two bitsets bitset<33> bitsetSubtract(bitset<32> x, bitset<32> y) {     bool borrow = false;     // bitset to store the sum of the two bitsets     bitset<33> ans;     for (int i = 0; i < 32; i++) {         ans[i] = fullSubtractor(x[i], y[i], borrow);     }     return ans; } // Driver Code int main() {     // Given Input     bitset<32> a(25);     bitset<32> b(15);      // Store the result of addition     bitset<33> result = bitsetSubtract(a, b);      cout << result;     return 0; } 

Output
000000000000000000000000000001010

Time Complexity: O(N), N is length of bitset
Auxiliary Space: O(N)


Next Article
Subtract two numbers without using arithmetic operators
author
sam_2200
Improve
Article Tags :
  • Bit Magic
  • C++
  • DSA
  • CPP-bitset
Practice Tags :
  • CPP
  • Bit Magic

Similar Reads

  • bitset operator[] in C++ STL
    bitset::operator[] is a built-in function in C++ STL which is used to assign value to any index of a bitset. Syntax: bitset_operator[index] = value Parameter: The parameter index specifies the position at which the value is to be assigned. Return Value: The function returns the value to the bit at t
    2 min read
  • Add two numbers without using arithmetic operators
    Given two integers a and b, the task is to find the sum of a and b without using + or - operators. Examples: Input: a = 10, b = 30Output: 40 Input: a = -1, b = 2Output: 1 Approach: The approach is to add two numbers using bitwise operations. Let's first go through some observations: a & b will h
    5 min read
  • Computing INT_MAX and INT_MIN with Bitwise operations
    Prerequisites : INT_MAX and INT_MIN in C/C++ and Applications. Arithmetic shift vs Logical shiftSuppose you have a 32-bit system : The INT_MAX would be 01111111111111111111111111111111 and INT_MIN would be 10000000000000000000000000000000. 0 & 1 in most-significant bit position representing the
    4 min read
  • Decimal to binary conversion without using arithmetic operators
    Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = ""
    8 min read
  • Subtract two numbers without using arithmetic operators
    Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use
    8 min read
  • Decimal to octal conversion with minimum use of arithmetic operators
    Given a decimal number n without floating-point. The problem is to convert the decimal number to octal number with minimum use of arithmetic operators. Examples: Input : n = 10 Output : 12 12 is octal equivalent of decimal 10. Input : n = 151 Output : 227 Approach: Following are the steps: Perform d
    8 min read
  • Bitwise Operators in C++
    In C+, Bitwise Operators are the operators that are used to perform bit-level operations on the integers. While performing these operations, integers are considered as sequences of binary digits. These operators are useful for low-level programming, system programming, and optimizing performance. C+
    6 min read
  • Bitwise Operators in C
    In C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number. The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They ar
    6 min read
  • Bitwise Algorithm in Python
    Bitwise algorithms refer to the use of bitwise operators to manipulate individual bits of data. Python provides a set of bitwise operators such as AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>). These operators are commonly used in tasks like encryption, com
    6 min read
  • std::bit_or in C++ with Examples
    The bit_or is an inbuilt function in C++ which is used to perform bitwise_or and return the result after applying the bitwise_or operation on it's arguments. Header File: #include <functional.h> Template Class: template <class T> struct bit_or; Parameters: It accepts a parameter T which
    2 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