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++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Create Stack of Bitset in C++?
Next article icon

How to Use Bit Manipulation Methods in C++

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Bit manipulation is a technique used for optimizing performance and memory usage in various programming scenarios. It is very useful from a Competitive Programming point of view. In this article, we will learn how we can use bit manipulation methods in C++ and provide examples to help you understand their practical applications.

Table of Content

  • Using Union and Struct for Efficient Bit Manipulation
    • C++ Program to Use Union and Struct for Bit Manipulation
  • Using std::bitset for Bit Manipulation
    • C++ Program to Use std::bitset for Bit Manipulation
  • Swap Using Bit Manipulation
    • C++ Program to Use Bit Manipulation for Swapping Two Integers

Using Union and Struct for Efficient Bit Manipulation

Bit manipulation involves performing operations on individual bits of integer variables using bitwise operators. Combining the union and struct keywords in C++ allow us to create a compound data structure that stores and manipulates different pieces of information within a single integer type, optimizing both memory and access speed.

C++ Program to Use Union and Struct for Bit Manipulation

In the below example, we define a BitSet object using union and struct to store a 32-bit integer, allowing for efficient bit-level access and manipulation.

C++
// C++ Program to Use Union and Struct for Bit Manipulation  #include <iostream>  using namespace std;  // Define a union BitSet with a bitfield structure and a // combined 32-bit integer union BitSet {     // Structure to define four 8-bit parts within the     // 32-bit integer     struct {         uint32_t part1 : 8;         uint32_t part2 : 8;         uint32_t part3 : 8;         uint32_t part4 : 8;     };     // Combined 32-bit integer representation     uint32_t combined; };  int main() {     // Declare a BitSet variable     BitSet bitSet;      // Assign values to each part of the BitSet     bitSet.part1 = 0x1A;     bitSet.part2 = 0x2B;     bitSet.part3 = 0x3C;     bitSet.part4 = 0x4D;      // Output the individual parts of the BitSet     cout << "Part1: " << bitSet.part1          << " Part2: " << bitSet.part2          << " Part3: " << bitSet.part3          << " Part4: " << bitSet.part4 << endl;      // Assign a combined value to the BitSet     bitSet.combined = 0x1A2B3C4D;      // Output the individual parts after assigning a     // combined value     cout << "Combined to Parts -> Part1: " << bitSet.part1          << " Part2: " << bitSet.part2          << " Part3: " << bitSet.part3          << " Part4: " << bitSet.part4 << endl;      return 0; } 

Output
Part1: 26 Part2: 43 Part3: 60 Part4: 77 Combined to Parts -> Part1: 77 Part2: 60 Part3: 43 Part4: 26 

Using std::bitset for Bit Manipulation

The std::bitset class in the C++ standard library provides an intuitive way to work with fixed-size sequences of bits. It offers constructors and bit manipulation functions that are more user-friendly than raw bitwise operations on integer types.

C++ Program to Use std::bitset for Bit Manipulation

The below example demonstrates basic operations using std::bitset, including bitwise NOT, XOR, and reset.

C++
// C++ Program to std::bitset for Bit Manipulation  #include <bitset> #include <iostream> using namespace std;  int main() {     // Create a bitset of size 8 initialized with binary     // string "10110011"     bitset<8> bitSet1("10110011");      // Perform bitwise NOT operation on bitSet1     bitset<8> bitSet2 = ~bitSet1;      // Output bitSet1 and bitSet2     cout << "bitSet1        : " << bitSet1 << endl;     cout << "bitSet2        : " << bitSet2 << endl;      // Perform bitwise XOR operation between bitSet1 and     // bitSet2     cout << "bitSet1 XOR bitSet2: " << (bitSet1 ^ bitSet2)          << endl;      // Reset all bits in bitSet1 to 0 and output the result     cout << "bitSet1 after reset  : " << bitSet1.reset()          << endl;      return 0; } 

Output
bitSet1        : 10110011 bitSet2        : 01001100 bitSet1 XOR bitSet2: 11111111 bitSet1 after reset  : 00000000 

Swap Using Bit Manipulation

Bitwise operators can also be used for tasks like swapping two integer variables. Using the XOR bitwise operator, you can swap two integers without needing a temporary variable.

C++ Program to Use Bit Manipulation for Swapping Two Integers

The below example demonstrates how to swap two integers using the XOR operator.

C++
// C++ Program to Use std::bitset for Bit Manipulation  #include <iostream>  using namespace std;  // Function to swap two integers using bitwise XOR void swapNumbers(int& a, int& b) {     // XOR operation to swap values without using a     // temporary variable     // a = a XOR b     a = a ^ b;     // b = (a XOR b) XOR b = a     b = a ^ b;     // a = (a XOR b) XOR a = b     a = a ^ b; }  int main() {     // initialize two numbers     int x = 15;     int y = 27;      cout << "Before swap -> x: " << x << " y: " << y          << endl;      // Call the swap function     swapNumbers(x, y);      cout << "After swap -> x: " << x << " y: " << y << endl;      return 0; } 

Output
Before swap -> x: 15 y: 27 After swap -> x: 27 y: 15 

Conclusion

Bit manipulation techniques in C++ can be highly efficient for certain tasks, such as optimizing performance and reducing memory usage. By using union and struct, std::bitset, and bitwise operators, you can perform a wide range of bit-level operations with ease. These examples provide a solid foundation for understanding and implementing bit manipulation in your C++ programs.


Next Article
How to Create Stack of Bitset in C++?

A

aakanksha21c
Improve
Article Tags :
  • C++ Programs
  • CPP-bitset
  • C++ Bit Manipulation
  • CPP Examples

Similar Reads

  • How to Count Set Bits in an Integer in C++?
    In binary representation of a number, a set bit is defined as the binary digit (bit) that is set to 1. In this article, we will learn how to count the set bits in a given integer in C++. Example Input: 13Output:The number of set bits in 13 (1101) is: 3Counting Set Bits in an IntegerTo count the set
    2 min read
  • How to Set, Clear, and Toggle a Single Bit in C++?
    In bit manipulation, setting a bit, clearing a bit, and toggling a single bit are basic operations. We can easily carry out these operations using the bitwise operators in C++. In this article, we will see how to set, clear, and toggle operations on the Kth bit. Example Input: N = 15, K = 0Output: S
    3 min read
  • How to Create Stack of Bitset in C++?
    In C++, a stack is a container adapter that provides a last-in, first-out (LIFO) type of data structure with two major operations, namely push and pop while Bitset is a container that can store N bits and provides constant-time operations to manipulate individual bits. In this article, we will learn
    2 min read
  • std::bit_xor in C++ with Examples
    The bit_xor is an inbuilt function in C++ which is used to perform bitwise_xor and return the result after applying the bitwise_xor operation on it's arguments. Header File: #include <functional.h> Template Class: template <class T> struct bit_xor; Parameters: It accepts a parameter T wh
    2 min read
  • bitset test() in C++ STL
    bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not. Syntax: bitset_name.test(index) Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not. Return Value: The function r
    2 min read
  • Add Two Numbers in C++
    Given two integers, the task is to add these integer number and print their sum in C++. Examples Input: a = 11, b = 9Output: 20Explanation: Sum of 11 + 9 = 20 Input: a = 1, b = 8Output: 9Explanation: Sum of 1 + 8 = 9 Add Two Numbers Using Addition OperatorIn C++, the simplest method for adding the t
    3 min read
  • bitset count() in C++ STL
    bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Syntax: int count() Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits. It returns the total number of ones or the number of se
    2 min read
  • Bit Magic C/C++ Programs
    Bit manipulation, also known as bit magic is the process of using bit-level operations to manipulate individual bits of a number. It uses bitwise operators such as AND, OR, XOR, right shift, etc. to manipulate, set, and shift the individual bits. This is used to improve the efficiency of our program
    3 min read
  • C++ Program For Decimal To Binary Conversion
    Binary Numbers uses only 0 and 1 (base-2), while Decimal Number uses 0 to 9 (base-10). In this article, we will learn to implement a C++ program to convert Decimal numbers to Binary Numbers. The below diagram shows an example of converting the decimal number 17 to an equivalent binary number. Recomm
    3 min read
  • C++ Program For Binary To Decimal Conversion
    The binary number system uses only two digits 0 and 1 to represent an integer and the Decimal number system uses ten digits 0 to 9 to represent a number. In this article, we will discuss the program for Binary to Decimal conversion in C++. Algorithm to Convert Binary Numbers to DecimalInitialize a v
    4 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