简体   繁体   中英

Invert (flip) last n bits of a number with only bitwise operations

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM