Turn off the rightmost set bit

来源:互联网 发布:淘宝50字通用好评 编辑:程序博客网 时间:2024/05/15 02:19

reference: 

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


Problem Definition:

Write a C function that unsets the rightmost set bit of an integer.


Solution:

Let the input number be n. 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.


Code:

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