Skip to content
Advertisement

Bitwise operator for simply flipping all bits in an integer?

I have to flip all bits in a binary representation of an integer. Given:

10101

The output should be

01010

What is the bitwise operator to accomplish this when used with an integer? For example, if I were writing a method like int flipBits(int n);, what would go in the body? I need to flip only what’s already present in the number, not all 32 bits in the integer.

Advertisement

Answer

The ~ unary operator is bitwise negation. If you need fewer bits than what fits in an int then you’ll need to mask it with & after the fact.

Advertisement