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 power of 2 or not ; Returns position of the only set bit in ' n ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; 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 count = 0 ; while ( n ) { n = n >> 1 ; ++ count ; } return count ; } int main ( void ) { int n = 0 ; 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 ; }