Spread the love

The main principle of this code logic is one by one right shift the set bit of given number ‘n’ until ‘n’ becomes 0. Count how many times we shifted to make ‘n’ zero. The final count is position of the set bit. This is Simple and efficient way because bitwise operator take shorter time to execute than arithmetic operator.

 

/* C program to find position of only set bit in a given number */

#include <stdio.h>
 
// A utility function to check whether n is power of 2 or not
int isPowerOfTwo(unsigned n)
{  return n && (! (n & (n-1)) ); }
 
// Returns position of the only set bit in 'n'
int findPosition(unsigned n)
{
    if (!isPowerOfTwo(n))
        return -1;
 
    unsigned count = 0;
 
    // One by one move the only set bit to right till it reaches end
    while (n)
    {
        n = n >> 1;
 
        // increment count of shifts
        ++count;
    }
 
    return count;
}
 
int main(void)
{
    int n = 0;
    int pos = findPosition(n);
    (pos == -1)? printf("n = %d, Invalid number\n", n):
                 printf("n = %d, Position %d \n", n, pos);
 
    n = 12;
    pos = findPosition(n);
    (pos == -1)? printf("n = %d, Invalid number\n", n):
                 printf("n = %d, Position %d \n", n, pos);
 
    n = 128;
    pos = findPosition(n);
    (pos == -1)? printf("n = %d, Invalid number\n", n):
                 printf("n = %d, Position %d \n", n, pos);
 
    return 0;
}

 

 

Suggested Reading

  1. Count number of 1s in given binary number
  2. Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
  3. Write a c program to implement XOR functionality with out using XOR(^) operator

If you like this Article, then don’t forget to Click on Social likes buttons.