Logo

Programming-Idioms

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

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

import static java.lang.Integer.toBinaryString;
String b = toBinaryString(n);
int i = b.lastIndexOf('1'), t;
t = i == -1 ? 0 : b.substring(++i).length();
import static java.lang.Integer.numberOfTrailingZeros;
int t = numberOfTrailingZeros(n);
import static java.lang.Integer.toBinaryString;
String p = ".+?(?<!0)(?=0+)",
       s = toBinaryString(n);
int t = s.replaceAll(p, "").length();
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...