What is the bitset::flip() function in C++?

In C++, the bitset::flip() function is used to flip the bits. This means to convert the ones to zeros and zeros to ones.

There are two functionalities that can be performed using this function:

  • Flip all the bits.
  • Flip the bit mentioned by a parameter pos.

This function is available in the bitset header file.

Syntax

The syntax of bitset::flip() function is shown below.

bitset& count();
bitset& count(size_t pos);

Parameters

The function accepts only an optional parameter as shown below.

  • pos: This parameter is an unsigned integer and specifies the bit’s position that needs to be flipped. If no value for pos is passed, then all the bits in the binary representation of the number will be flipped.

Return value

The function returns a new bitset object that contains the flipped values.

Code

Let’s have a look at the code.

#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<4> b1 = 10;
cout << "Original value: " << b1 << endl;
cout << "Flipped all bits: " << b1.flip() << endl;
cout << "Flipped second bit : " << b1.flip(2);
return 0;
}

Explanation

  • In lines 1 and 2, we import the required header files.
  • In line 6, we create one bitset object that can store 4 bits. This object will contain the binary representation of the integer 10.
  • In line 7, we print the original bit representation of the integer 10.
  • In line 8, we call the flip() function and print the flipped values.
  • In line 9, we again call the flip() function, but this time we pass the argument as 2 to flip only the second bit and print the new binary representation.

In this way, we can flip the bits of any number using the flip() function in C++.

Free Resources