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)
[ad type=”banner”]

Program:

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%23include%3Cmath.h%3E%0A%20%0Aunsigned%20int%20getFirstSetBitPos(int%20n)%0A%7B%0A%20%20%20return%20log2(n%26-n)%2B1%3B%0A%7D%0A%20%0Aint%20main()%0A%7B%0A%20%20%20%20int%20n%20%3D%2012%3B%0A%20%20%20%20printf(%22%25u%22%2C%20getFirstSetBitPos(n))%3B%0A%20%20%20%20getchar()%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/] [ad type=”banner”]

Categorized in: