How to flip binary bits?

i need to flip all the bits except the first set bit from left side
like - > 001010111
res-> 001101000

i have did this with first converting to string and the fliping
how can we do the same with bitwise operators ?

        string s = bitset<32>(n).to_string();
        bool ok = false;
        for(int i=0; i<s.size(); i++){
                    s[i] = '1';
                else s[i] = '0';
                ok = true;
        bitset<32> b(s);
        return b.to_ulong();
1 Like
    int x=10;
	int n= log2(x);
	n=1<<n;         //Finding the most significant bit
	int ans=x^(n-1);   // Flipping all bits except most significant bit

You can also find most significant bit in O(1) also.

1 Like