Logo

Programming-Idioms

  • PHP
  • Fortran
  • Ruby

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

t = n.digits(2).index(1)
t = trailz(n)
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...