开发者

Unset the rightmost set bit [duplicate]

This question already has answers here: Closed 12 years ago.

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 开发者_如何学Crightmost 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?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜