How to count efficiently the number of trailing zeros in a binary representation of an integer number?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With