Algorithm Bit Algorithms:

Turn off the rightmost set bit

Turn off the rightmost set bit - Bit Algorithm - Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit .

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

Examples:

Input:  12 (00...01100)
Output: 8 (00...01000)

Input:  7 (00...00111)
Output: 6 (00...00110)

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.

c
#include<stdio.h>
 
/* unsets the rightmost set bit of n and returns the result */
int fun(unsigned int n)
{
  return n&(n-1);
}    
 
/* Driver program to test above function */
int main()
{
  int n = 7;
  printf("The number after unsetting the rightmost set bit %d", fun(n));
 
  getchar();
  return 0;
}
See also  Java Programmming - Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array

About the author

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X