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 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 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++
1<<b is not defined by the C standard if b is the number of bits in an int or is one less than that. (If it is one less, the behavior is not defined because the value overflows. If it is equal to the width, it is not defined because the shift operator is limited to a shift of less than the full width.)11101001 gives 10010111. It means writing the bit string backwards.flipBits(0x32,6&5) which should give the same result than your example since 6&5 is 4? With define, you need also parenthesis around each parameter you use, since define works with dumb substitution. Demo ideone.com/qHefN51u<<(b) than 1<<(b)