Skip to content
Related Articles

Related Articles

bitset::flip() in C++ STL
  • Last Updated : 06 Jun, 2020

bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only.

Syntax:

bitset_name.flip(int pos)

Parameter: The function accepts a parameter pos which is not mandatory. If a parameter pos is passed, it flips the bit at the index pos only(the index pos is calculated starting from the right). In case no parameter is passed, it flips all the bit values converting zeros to ones and ones to zeros.

Return Value: The function flips all the bit values according to the parameter passed or not and returns the new binary representation of the number.

Below programs illustrates the bitset::flip() function.



Program 1:




// CPP program to illustrate the
// bitset::flip() function
// when no parameter is passed
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    bitset<4> b1(string("1100"));
    bitset<6> b2(string("010010"));
  
    // Printing the bitset after flipping the bits
    cout << b1 << " after applying flip() function returns ";
    cout << b1.flip() << endl;
  
    cout << b2 << " after applying flip() function returns ";
    cout << b2.flip();
  
    return 0;
}
Output:
0011 after applying flip() function returns 1100
101101 after applying flip() function returns 010010

Program 2:




// CPP program to illustrate the
// bitset::flip() function
// when parameter is passed
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // Initialization of bitset
    bitset<4> b1(string("1100"));
    bitset<7> b2(string("0100100"));
  
    // Printing the bitset after flipping the bits
    cout << b1 << " after applying flip(3) function returns ";
    cout << b1.flip(3) << endl;
  
    cout << b2 << " after applying flip(6) function returns ";
    cout << b2.flip(6);
  
    return 0;
}
Output:
0100 after applying flip(3) function returns 1100
1100100 after applying flip(6) function returns 0100100
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :