Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count trailing zeros in a binary representation of an integer number with C#

How to count efficiently the number of trailing zeros in a binary representation of an integer number?

like image 288
abel406 Avatar asked Dec 03 '22 21:12

abel406


1 Answers

Here's a nice, quick and easy implementation:

public static int NumberOfTrailingZeros(int i)
{
    return _lookup[(i & -i) % 37];
}

private static readonly int[] _lookup =
    {
        32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17,
        0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
    };

(Taken from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightModLookup.)

like image 58
LukeH Avatar answered Dec 05 '22 10:12

LukeH