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.
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
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.
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).
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With