Wednesday, August 4, 2010

First bit set in an Integer

Write a C code which returns the position of the first bit set.fot eg. for number 104(1101000) output will be 4.

You need to right shift the number untill the number becomes zero and count the number of times right shifted, then you subtract it from the size of an interger (32 bit on a 32 bit machine), you will get the answer. Here is the code for your reference.

int fbs(unsigned int num)
{
    int pos = -1;
    while(num!=0)
    {
        num <<= 1;
        pos++;
    }
    return 32 - pos;
}

No comments:

Post a Comment