Reputation: 2231
Given a binary integer, how can I invert (flip) last n bits using only bitwise operations in c/c++?
For example:
// flip last 2 bits
0110 -> 0101
0011 -> 0000
1000 -> 1011
Upvotes: 2
Views: 2639
Reputation: 177
You can flip last n bits of your number with
#define flipBits(n,b) ((n)^((1u<<(b))-1))
for example flipBits(0x32, 4)
will flip the last 4 bits and result will be 0x3d
this works because if you think how XOR works
0 ^ 0 => 0
1 ^ 0 => 1
bits aren't flipped
0 ^ 1 => 1
1 ^ 1 => 0
bits are flipped
(1<<b)-1
this part gets you the last n bits
for example, if b is 4 then 1<<4
is 0b10000
and if we remove 1 we get our mask which is 0b1111
then we can use this to xor with our number to get the desired output.
works for C and C++
Upvotes: 6