2

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 
8
  • @paulsm4: I think you will find it's not that simple. Commented Jan 5, 2019 at 23:53
  • @paulsm4 notice I said last n bits, not the whole number, which is not as trivial Commented Jan 5, 2019 at 23:54
  • OK, now it is clearer. But what have you tried so far ? Commented Jan 5, 2019 at 23:57
  • 1
    @harold I updated the title and the question to clarify the intention. Thanks for pointing out Commented Jan 5, 2019 at 23:57
  • 2
    In that case we have set n bits and XOR by that mask Commented Jan 5, 2019 at 23:58

1 Answer 1

6

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++

Sign up to request clarification or add additional context in comments.

12 Comments

Could be an acceptable answer if you would put the define expression between parenthesis, in order to avoid issues with preprocessing an priority. Would be much better with an inline function or a template function.
The behavior of 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.)
@MuhsinFatih: reversing all the bits of e.g. 11101001 gives 10010111. It means writing the bit string backwards.
Better now :-) But have you tried 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/qHefN5
Better to use 1u<<(b) than 1<<(b)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.