Bitwise operator for simply flipping all bits in an integer?
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.
Simply use the bitwise not operator ~
.
int flipBits(int n) { return ~n;}
To use the k least significant bits, convert it to the right mask.
(I assume you want at least 1 bit of course, that's why mask starts at 1)
int flipBits(int n, int k) { int mask = 1; for (int i = 1; i < k; ++i) mask |= mask << 1; return ~n & mask;}
As suggested by Lưu Vĩnh Phúc, one can create the mask as (1 << k) - 1
instead of using a loop.
int flipBits2(int n, int k) { int mask = (1 << k) - 1; return ~n & mask;}
There is a number of ways to flip all the bit using operations
x = ~x; // has been mentioned and the most obvious solution.x = -x - 1; or x = -1 * (x + 1);x ^= -1; or x = x ^ ~0;