VOOZH about

URL: https://www.geeksforgeeks.org/cpp/bit-manipulation-methods-in-cpp/

⇱ How to Use Bit Manipulation Methods in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Use Bit Manipulation Methods in C++

Last Updated : 23 Jul, 2025

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

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.


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

The 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.


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.


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.

Comment