Bitwise operator for simply flipping all bits in an integer?

Naftuli Kay picture Naftuli Kay · Jun 15, 2011 · Viewed 95.4k times · Source

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.

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Jun 15, 2011

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.