Logo

Programming-Idioms

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

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();

Simple but not too elegant. Heavy use of LINQ.
#include <stdio.h>
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);

New implementation...