Logo

Programming-Idioms

  • Go
  • Fortran

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 = trailz(n)
import "math/bits"
t := bits.TrailingZeros(n)

n has type uint
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...