How to Use Bit Manipulation Methods in C++

Jinku Hu Feb 02, 2024
  1. Use union Combined With struct to Implement Efficient Bit Manipulation Data Structure in C++
  2. Use std::bitset to Conduct Bit Manipulation Operations in C++
  3. Use Bit Manipulation to Swap Two Integers in C++
How to Use Bit Manipulation Methods in C++

This article will explain how to use bit manipulation methods in C++.

Use union Combined With struct to Implement Efficient Bit Manipulation Data Structure in C++

Bit manipulation can be considered a broad name for common operations conducted on integer variables with bitwise operators. Bitwise shift operators are often used to substitute common arithmetic operations on numbers while offering better performance. Note that integer types are commonly used to implement a compound data structure by storing different information in separate bit sets of the given type. This method can be used to minimize the memory footprint of data and also improve access speeds.

In this case, we utilize union and struct keywords to implement a special object named BitSet for storing the uint32_t type integer, which can store 32 bits. Mind that, union defines a special kind of class in C++ that can have multiple data members, but only one of them can store valid value at any given time. As a result, the class object usually takes up the amount of the biggest data member. The following example also demonstrates the usage of bitfields, making predefined sets of bits in integers accessible using the struct member notation. The resulting BitSet can be manipulated using the regular assignment operation for each member or using bit manipulations.

#include <iostream>

using std::cout;
using std::endl;

union BitSet {
  struct {
    uint32_t b1 : 8;
    uint32_t b2 : 8;
    uint32_t b3 : 8;
    uint32_t b4 : 8;
  };
  uint32_t bb;
};

int main() {
  BitSet set1 = {'a', 'b', 'c', 'd'};
  cout << set1.b1 << " " << set1.b2 << " " << set1.b3 << " " << set1.b4 << endl;

  set1.bb = 'a' | ('b' << 8) | ('c' << 16) | ('d' << 24);

  cout << set1.b1 << " " << set1.b2 << " " << set1.b3 << " " << set1.b4 << endl;

  return EXIT_SUCCESS;
}

Output:

97 98 99 100
97 98 99 100

Use std::bitset to Conduct Bit Manipulation Operations in C++

std::bitset is part of the C++ standard library and represents a fixed-size sequence of bits. It provides an intuitive constructor and bit modifier/access functions that are easier to utilize than raw operations on integer types using bitmasks. std::bitset supports all bitwise operators and compares similar objects. The next code snippet demonstrates some of the basic operations on std::bitset objects.

#include <bitset>
#include <iostream>

using std::cout;
using std::endl;

int main() {
  std::bitset<8> bs1("11001001");
  std::bitset<8> bs2(~bs1);

  cout << "bs1        : " << bs1 << endl;
  cout << "bs2        : " << bs2 << endl;
  cout << "bs1 XOR bs2: " << (bs1 ^ bs2) << endl;
  cout << "bs1 reset  : " << bs1.reset() << endl;

  return EXIT_SUCCESS;
}

Output:

bs1        : 11001001
bs2        : 00110110
bs1 XOR bs2: 11111111
bs1 reset  : 00000000

Use Bit Manipulation to Swap Two Integers in C++

Apart from arithmetic operations, some bitwise operators provide useful features that solve many common programming problems. One such example is to swap two integer variables using the XOR bitwise operator. Note that XOR swap does not guarantee better performance than regular swap using the temporary variable and may even be slower on contemporary desktop and mobile application processors.

#include <bitset>
#include <iostream>

using std::cout;
using std::endl;

void SwapIntegers(int &x, int &y) {
  y = x ^ y;
  x = x ^ y;
  y = x ^ y;
}

int main() {
  int k = 5;
  int m = 9;

  cout << "k: " << k << " m: " << m << endl;
  SwapIntegers(k, m);
  cout << "k: " << k << " m: " << m << endl;

  return EXIT_SUCCESS;
}

Output:

k: 5 m: 9
k: 9 m: 5
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook