Logo

Programming-Idioms

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

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

int t = 0;

if(n != 0)
{
    while((n & 1) == 0)
    {
        t++;
        n >>= 1;
    }
}
else
{
    t = 8 * sizeof(int);
}
using System;
using System.Linq;
var t = Convert.ToString(n, 2)
    .Reverse()
    .TakeWhile(i => i == '0')
    .Count();
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);
t = n.bitLength - 1 - n.toRadixString(2).lastIndexOf('1');
t = n.toRadixString(2)
	.split('')
	.reversed
	.takeWhile((e) => e == '0')
	.length;
var t = 0;
while (n.isEven && n != 0) {
  t++;
  n = n >> 1;
}
trailingZeros(Num) ->
        trailingZeros(Num, 0).

trailingZeros(Num, Count) when Num band 1 == 0 ->
        trailingZeros(Num div 2, Count + 1);
trailingZeros(_, Count) -> Count.
t = trailz(n)
import "math/bits"
t := bits.TrailingZeros(n)
import static java.lang.Integer.toBinaryString;
int t;
if (n % 2 != 0) t = 0;
else {
    String b = toBinaryString(n);
    t = b.replaceAll(".+?(?<!0)(?=0+)", "").length();
}
import static java.lang.Integer.numberOfTrailingZeros;
int t = numberOfTrailingZeros(n);
import static java.lang.Integer.toBinaryString;
String b = toBinaryString(n);
int i = b.lastIndexOf('1'), t;
t = i == -1 ? 0 : b.substring(++i).length();
function Trail(n: Integer): Integer;
var
  Mask: Integer;
begin
  T := 0;
  while (T < SizeOf(Integer)*8) do
  begin
    Mask := 1 shl T;
    if (n and Mask) <> 0 then Exit;
    Inc(T);
  end;
end;

begin
  writeln(Trail(112),' (should be 4)');
end.
$s = sprintf '%b', $n; 
$n = length $s; 
$t++ while !substr($s, --$n, 1) && $n >= 0; 
$t = sprintf('%b', $n) =~ /(0+)$/ ? length($1) : 0;
t = bin(n)[::-1].find('1')
b = len(s := format(n, 'b'))
t = b - len(s.rstrip('0'))
t = n.digits(2).index(1)
let t = n.trailing_zeros();

New implementation...