Toggle all bits after most significant bit | CPP program to toggle set bits starting from MSB ; Returns a number which has all set bits starting from MSB of n ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int setAllBitsAfterMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } void toggle ( int & n ) { n = n ^ setAllBitsAfterMSB ( n ) ; } int main ( ) { int n = 10 ; toggle ( n ) ; cout << n ; return 0 ; }