Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 932
Naftuli Kay Avatar asked Jun 14 '11 23:06

Naftuli Kay


People also ask

Which bitwise operator is used for flipping bits?

Binary One's Complement Operator is unary and has the effect of 'flipping' bits.

How do you flip all bits in a number?

Examples: Input : 11 Output : 4 (11)10 = (1011)[2] After inverting the bits, we get: (0100)2 = (4)10. Input : 10 Output : 5 (10)10 = (1010)2. After reversing the bits we get: (0101)2 = (101)2 = (5)10.

How do you flip a bit value?

To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1 shifted k bits to the left. is valid in C, Java, Python and a few other languages (provided the variables are appropriately defined).


2 Answers

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.

like image 197
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 07:09

Ignacio Vazquez-Abrams


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; } 
like image 26
George Avatar answered Sep 30 '22 05:09

George