# Which bit position is on in 32bit?

103 views

In a 32 bit only one bit is on, with out using loops, goto, or recursion how to find out which position is on?
example : 4 ---> 2nd bit ( 0000 0100)

posted Sep 26, 2014

+1 vote

Only single is on if the number is power of 2 .
Example if number is 4 , 2power2 =4 implies 2nd bit is on.

Ya you are right, the number will be a power of two only as there only one bit is on.
But the restriction is we can't use any loop or recursion.
needed ans is a single line statement.

Any comment or suggestion are welcome.
int is_power_of_two(unsigned n)
{
return n && (! (n & (n-1)) );
}

But you can not avoid the loop as after finding that number if power of two then you need to run a loop for finding the position.
I think I have a solution. I am posting bellow.
+1 vote

Try something like this

``````int is_power_of_two(int n)
{
return n && (! (n & (n-1)) );
}

int find_position(int n)
{
if (!is_power_of_two(n))
return -1;

int i = 1, position = 1;

while (!(i & n))
{
i = i << 1;
++position;
}

return position;
}
``````
+1 vote
``````int main()
{
int x = 128;        // change the number for validate
int bit_pos = 0;

bit_pos = ((( x & 0xFFFF0000 ) != 0) << 4 ) +
((( x & 0xFF00FF00 ) != 0) << 3 ) +
((( x & 0xF0F0F0F0 ) != 0) << 2 ) +
((( x & 0xCCCCCCCC ) != 0) << 1) +
(( x & 0xAAAAAAAA ) != 0);

printf("bit_possition which is on : %d\n", bit_pos);
return 0;
}
``````

2 : Or you can use ffs() "find first bit set in a word" (it counts from 1 not from 0)
I didn't sure that this function use or didn't use loop internally.

``````int main()
{
int num = 32;

printf("bit_postion : %d\n", fss(num));

return 0;
}
``````
Similar Questions

I am expecting zero value of 16-bit signed value 0x8000 after left shift by 2.

Following is my code

``````int main()
{
register signed short val1 = 0x8000 ;
signed short val2 ;
val2 = ( ( val1 > 2 ) ; /* val2 should be 0. */
printf( "nval2 is :%xn", val2 ) ; /* But Val2 is ffff8000 */
return 0 ;
}

\$ gcc myfile.c
\$ ./a.out
``````

I have verified the same behavior with 32-bit compilers and expected (val2=0) with 16-bit compiler. I can correct this by shifting 18 in place of 2 as a workaround. I want some verify my understanding for this point and another way to get expected result (if any).