Reset the Rightmost Bit

Possible duplicates:
How do you set, clear, and switch one bit in C?
Low bit deletion

n is a positive integer. How can I not set its rightmost bit?

Say n = 7 => n = 0111. I want 0110 as output. Is there a simple bitwise hack to achieve the goal?

+8
c ++ c math algorithm bit-manipulation
source share
3 answers

Try n & (n-1) where & bitwise and

 n = 7 n - 1 =6 n & (n-1)=> 0 1 1 1 (7) & 0 1 1 0 (6) --------- 0 1 1 0 (done!) 

EDIT (in response to comment provided by Forest)

 n = 6 n - 1 = 5 n & (n-1)=> 0 1 1 0 (6) & 0 1 0 1 (5) --------- 0 1 0 0 (done!) 
+18
source share

Your question is not clear.

If you just want to reset bit 0, here are a few methods (with slight variations depending on your types):

 x &= -2; x &= ~1; x -= (x&1); 

If you want to undo the least significant bit among the bits that are set, here are a few ways:

 x &= x-1; x -= (x&-x); 

Note that x&-x is the least significant bit of x , at least when x is unsigned or two-component. If you want to do any bit arithmetic like this, you should only use unsigned types, since signed types have behavior defined by the implementation of bitwise operations.

+4
source share
 unsigned int clr_rm_set_bit(unsigned int n) { unsigned int mask = 1; while(n & mask) { mask <<= 1; } return n & ~mask; } 
0
source share

Source: https://habr.com/ru/post/651114/


All Articles