Bit Algorithms:

Position of rightmost set bit

Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer.

Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer.

I/P    18,   Binary Representation 010010
O/P   2
I/P    19,   Binary Representation 010011
O/P   1

Let I/P be 12 (1100)

Algorithm: (Example 18(010010))

1. Take two's complement of the given no as all bits are reverted
except the first '1' from right to left (10111)

2  Do an bit-wise & with original no, this will return no with the
required one only (00010)

3  Take the log2 of the no, you will get position -1 (1)

4  Add 1 (2)

Program:

C Programming
#include<stdio.h>
#include<math.h>
 
unsigned int getFirstSetBitPos(int n)
{
   return log2(n&-n)+1;
}
 
int main()
{
    int n = 12;
    printf("%u", getFirstSetBitPos(n));
    getchar();
    return 0;
}
See also  Compute the minimum or maximum of two integers without branching

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