Consider I have a number 100101 of length 6. I wish to flip bits starting from position 2 to 5 so my answer will be 111011. I know that I can flip individual bits in a loop. But is there an efficient way of doing this without a for loop?
2 Answers
If I understand you correctly, try
namespace { unsigned flip(unsigned a) { return a ^ 0b011110u; } } // namespace Just adjust the constant to the actual bits you want to flip by having them as 1's in the constant.
On the otherhand, if you need just to update an individual variable you also use
unsigned value = 0b100101u; value ^= 0b011110u; assert(value == 0b111011u); EDIT And here is the same using std::bitset<6u> and C++98:
#include <bitset> #include <cassert> int main() { std::bitset<6u> const kFlipBit2to6WithXor(0x1Eu); // aka 0b011110u std::bitset<6u> number(0x25u); // aka 0b100101u number ^= kFlipBit2to6WithXor; assert(number.to_ulong() == 0x3Bu); // aka 0b111011u return 0; } 2 Comments
Alan Birtles
XOR is more likely to give the result the OP was looking for than OR
Pete Becker
Now do the other one — flip the bits, so that 0s become 1s and 1s become 0s. Hint: you only have to change one character in your code.
1? And is it big-endian or little endian?