Logo

Programming-Idioms

  • JS

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 = sprintf('%b', $n) =~ /(0+)$/ ? length($1) : 0;

sprintf %b converts $n from an integer to a string of 1's and 0's. This is then matched (using the =~ operator) against a regular expression which looks for one or more zeroes at the end of the string. The parens around 0+ form a capture group which is accessible via the variable $1 and will contain the string of trailing 0's. If the match succeeds, then the length of $1 is computed and returned; if not, then a length of zero is returned.
$s = sprintf '%b', $n; 
$n = length $s; 
$t++ while !substr($s, --$n, 1) && $n >= 0; 

Converts the integer in scalar variable $n into a string of zeros and ones. Extract characters from the end of the string until a non-zero is found. (A character 0 is treated as false, a 1 as true.) Stop when we reach the start of the string.
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...