Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset the rightmost set bit [duplicate]

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?

like image 237
Edward Norton Avatar asked Jan 16 '11 05:01

Edward Norton


People also ask

What is rightmost set bit?

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)

Which of the following Bitwise operation turns off the rightmost?

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.


2 Answers

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!)
like image 95
Prasoon Saurav Avatar answered Oct 04 '22 10:10

Prasoon Saurav


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.

like image 20
R.. GitHub STOP HELPING ICE Avatar answered Oct 04 '22 12:10

R.. GitHub STOP HELPING ICE