Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Erlang

Idiom #262 Count trailing zero bits

Assign to t the number of trailing 0 bits in the binary representation of the integer n.

E.g. for n=112, n is 1110000 in base 2 ⇒ t=4

trailingZeros(Num) ->
        trailingZeros(Num, 0).

trailingZeros(Num, Count) when Num band 1 == 0 ->
        trailingZeros(Num div 2, Count + 1);
trailingZeros(_, Count) -> Count.
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...