I've written a function trailing_zeroes(int n)
that returns the number of the trailing zeroes in the binary representation of a number.
Example: 4
in binary is 100
, so the function in this case returns 2
.
unsigned trailing_zeroes(int n) {
unsigned bits;
bits = 0;
while (n >= 0 && !(n & 01)) {
++bits;
if (n != 0)
n >>= 1;
else
break;
}
return bits;
}
The reason of the if
statement is because in case n
equals to 0, there will be a loop.
I think it's pretty ugly this code written like this; is there a better way?
I want to avoid the break
statement inside the while
, because a lot of people told me that using that statement inside while/for
sometimes could be "informal". I thought to rewrite the function like this, but I don't think it's the best way to do it:
unsigned bits;
if (n == 0)
return bits = 1;
bits = 0;
while (!(n & 01)) {
++bits;
n >>= 1;
}
__builtin_ctz
. – Eckardstd::string
and inspect that one. – Fretwelln
). – Blenreturn bits = 1;
is a bit bizarre; simplyreturn 1;
would be more sensible, though the compiler will almost certainly convert the code as if you wrote that anyway.) – Cheekyx
is0
the result is undefined (why ?) – Castellany__builtin_ctz
in GCC gives an undefined result for zero, but (guesswork) it is likely because the native implementations on different platforms yields different results — and it is likely that the two results are zero and the number of bits in the integer type. But rather than make the result platform-specific, GCC makes it undefined, so portable code doesn't call the function with an argument that's zero. – Cheeky