Possible Duplicates:
How do you set, clear and toggle a single bit in C?
Removing lowest order bit
n
is a positive integer. How can its rightmost set bit be unset?
Say n
= 7
=> n = 0111.
I want 0110
as the output. Is there any simple bitwise hack to achieve the goal?
Then the rightmost set bit in n will be the position of the only set bit in the result. Note that if n is odd, we can directly return 1 as the first bit is always set for odd numbers. For example, the number 20 in binary is 00010100 , and the position of the rightmost set bit is 3. 00010100 & (n = 20)
n-1 would have all the bits flipped after the rightmost set bit (including the set bit). So, doing n&(n-1) would give us the required result.
Try n & (n-1)
where &
is 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 the comment given 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!)
Your question is unclear.
If you just want to unset bit 0, here are some methods (with slight variations in behavior depending on your types involved):
x &= -2;
x &= ~1;
x -= (x&1);
If you want to unset the lowest bit among the bits that are set, here are some ways:
x &= x-1;
x -= (x&-x);
Note that x&-x
is equal to the lowest bit of x
, at least when x
is unsigned or twos complement. If you want to do any bit arithmetic like this, you should use only unsigned types, since signed types have implementation-defined behavior under bitwise operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With