[C/C++] Finding trailing 0s in a binary number

int bitcount(unsigned __int64 value)
{
    if (!value)
        return SOME_DEFAULT_VALUE;

    value &= -value;
    unsigned int lsb = (unsigned) value | (unsigned) (value >> 32);
    return (int)(((((((((((unsigned) (value >> 32) != 0) * 2)
            + ((lsb & 0xffff0000) != 0)) * 2)
            + ((lsb & 0xff00ff00) != 0)) * 2)
            + ((lsb & 0xf0f0f0f0) != 0)) * 2)
            + ((lsb & 0xcccccccc) != 0)) * 2)
            + ((lsb & 0xaaaaaaaa) != 0);
}
int bitcount(unsigned char x)
{
    int b;
    for(b=0; b<7 && !(x&1); x>>=1) b++;
    
    return b;
}

Reference

https://stackoverflow.com/questions/7812044/finding-trailing-0s-in-a-binary-number

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.