How to Use Bit Manipulation Methods in C++
Last Updated :
17 Jul, 2024
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.
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;
}
OutputPart1: 26 Part2: 43 Part3: 60 Part4: 77
Combined to Parts -> Part1: 77 Part2: 60 Part3: 43 Part4: 26
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;
}
OutputbitSet1 : 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;
}
OutputBefore 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.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read