Unset the rightmost set bit [duplicate]

橙三吉。 提交于 2019-11-30 08:28:41

问题


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?


回答1:


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!)



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4703964/unset-the-rightmost-set-bit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!