bitset::flip() in C++ STL

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 "
         << b1.flip() << endl;
  
    cout << b2 << " after applying flip() function returns "
         << b2.flip();
  
    return 0;
}

chevron_right


Output:

0011 after applying flip() function returns 0011
101101 after applying flip() function returns 101101

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 "
         << b1.flip(3) << endl;
  
    cout << b2 << " after applying flip(6) function returns "
         << b2.flip(6);
  
    return 0;
}

chevron_right


Output:

0100 after applying flip(3) function returns 0100
1100100 after applying flip(6) function returns 1100100


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.