Trailing Zeros - C

Viewed 1091

I need a program that returns the number of trailing zeros in the binary rapresentation of a number. I found online a function written in C but I don't understand how it works

This is the function:

unsigned tzr(unsigned x) 
{
    unsigned n; /* number of bits */

    n = 0;
    if (!(x & 0x0000FFFF)) { n += 16; x >>= 16; }
    if (!(x & 0x000000FF)) { n +=  8; x >>=  8; }
    if (!(x & 0x0000000F)) { n +=  4; x >>=  4; }
    if (!(x & 0x00000003)) { n +=  2; x >>=  2; }

    n += (x & 1) ^ 1; // anyway what does this do ? 

    return n;
}

Now I've really tried to understand how this works but I don't get it. I really need someone who could explain it to me, I find this code very complicated.

And about those hexadecimal constants, these are their values:

0x0000FFFF = 65535
0x000000FF = 255
0x0000000F = 15
0x00000003 = 3

Now, why the program uses those values and makes a bitwise AND with the number?

Then I know that if you want to handle big numbers you must
use a while instead of the first if statement, like this:

while (!(x & 0x0000FFFF)) { bits += 16; x >>= 16; } // why should I need this ?

But I don't know why ! What's the difference about using a while instead of an if in this case?

5 Answers
Related