In GCC you can use a built-in function:
Built-in Function: int __builtin_clz (unsigned int x)
Returns the number of leading 0-bits in x
, starting at the most significant bit position. If x
is 0, the result is undefined.
You have to negate the input using binary negation: ~x
(0 will become 1, and vice versa).
Here is a more academic solution:
#include <stdio.h>
#include <stdint.h>
int leftCount (unsigned int value) {
if (~value == 0) {
return 32; // you said your ints were 32 bits, so the code assumes that
}
int result = 0;
while (value >> 31 == 1) { // test if highest bit is set
value <<= 1; // shift the input to the left
++result; // one more bit was seen
}
return result;
}
int main (void) {
unsigned int value;
while (scanf ("%i", &value) == 1) {
printf ("leftCount(0x%x) == %u\n", value, leftCount(value));
}
return 0;
}