Originally Posted by
christop
I'd write it much simpler than that by starting i at 1 and counting how many times it can be multiplied by 2 (or shifted left one bit):
Code:
#include <stdio.h>
int main(void)
{
unsigned long long i = 1;
int counter = 0;
while (i) {
i *= 2; // or i <<= 1;
++counter;
}
printf("%d\n", counter);
return 0;
}
Code:
#include <stdio.h>
int main( void )
{
unsigned int i = 1;
int counter = 0;
while (i)
{
i <<= 1;
counter++;
}
printf("%d\n", counter);
return 0;
}
This one worked fine, as long as I declare i as unsigned int.
Code:
#include <stdio.h>
#include <limits.h>
int main( void )
{
unsigned int i = UINT_MAX;
int counter = 1;
while ( i >>= 1 )
counter++;
printf( "%d\n", counter );
return 0;
}
was probably the most elegant one. And most portable maybe?