text: Find position of the only set bit | C program to find position of only set bit in a given number ; A utility function to check whether n is a power of 2 or not . goo . gl / 17 Arj See http : ; Returns position of the only set bit in ' n ' ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in ' i ' ; increment position ; Driver program to test above function
code: #include <stdio.h> NEW_LINE int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned i = 1 , pos = 1 ; while ( ! ( i & n ) ) { i = i << 1 ; ++ pos ; } return pos ; } int main ( void ) { int n = 16 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; return 0 ; }