Off rightmost set bit of an integer

亡梦爱人 提交于 2021-01-05 04:44:57

问题


All I need to off the rightmost set bit. My approach is to find the position of right most bit, then off that bit. I write this code to do so..

int POS(int n)
{
    int p=0;

    while(n)
    {
        if(n%2==0)
        {
            p++;
        }
        else
        {
            break;
        }  
        n=n/2;
     }
     return p;
  }

 int main(void)
 {

 int n=12;
 int p = POS(n);
 printf("%d \n", n&~(1<<p));

 return 0;

 }

Is there any simplest way?


回答1:


Read http://www.geeksforgeeks.org/turn-off-the-rightmost-set-bit/

/* unsets the rightmost set bit of n and returns the result */
int fun(unsigned int n)
{
  return n&(n-1);
} 



回答2:


If you're talking about clearing the least significant bit that is currently set, use:

num = num & (num - 1);

The reasoning behind this is that a number like xxxx1000 (where x means "original value") will become xxxx0111 when you subtract one, and anding those two values gives:

  xxxx1000
& xxxx0111
  --------
  xxxx0000

clearing the rightmost one-bit.


On the off-chance I've misunderstood the question, if you want to set the rightmost (least significant) bit to zero, all you need is:

num = num - (num % 2);

This simply subtracts one from odd numbers and nothing from even numbers, effectively making the result binary xxxxxxx0.

For clearing a specific bit where bit 0 is the least significant, use:

num = num & ~(1 << bitpos);

This sets up a bit mask ike 00001000 and inverts it to 11110111 so that anding it will clear the relevant bit:

  xxxxxxxx
& 11110111
  --------
  xxxx0xxx

Just make sure you're using unsigned integers, it may not behave as you expect for signed values.




回答3:


I think you are looking for this:

printf("%d \n", n&(n-1));

This actually works. Because:

1010 = 10        111 = 7
1001 =  9        110 = 6
----             ---
1000 =  8        110 = 6

Hope you understand the idea..

ref: Turn off the rightmost bit of an integer (read this)

Or you can modify your code like followings:

int POS(int n)
{
    int p=0;

    while(!(n&1))
    {
        p++;
        n=n>>1;
    }

    return p;
}



回答4:


I think that the simplest way is to use expression

n & n - 1

Also you can use the following straightforward approach

#include <iostream>
#include <iomanip>

int reset_bit( int x )
{
    if ( x != 0 )
    {
        unsigned int n = 1;
        while ( !( x & n ) ) n <<= 1;
        x ^= n; 
    }

    return x;
}

int main()
{
    for ( int x = 1; x < 16; ++x )
    {
        std::cout << std::hex << x << '\t' << reset_bit( x ) << std::endl;
    }

    return 0;
}

The output is

3   2
4   0
5   4
6   4
7   6
8   0
9   8
a   8
b   a
c   8
d   c
e   c
f   e


来源:https://stackoverflow.com/questions/27540201/off-rightmost-set-bit-of-an-integer

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