Position of least significant bit that is set

Posted by peterchen on Stack Overflow See other posts from Stack Overflow or by peterchen
Published on 2009-04-16T16:54:48Z Indexed on 2010/05/14 2:04 UTC
Read the original article Hit count: 317

I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.

A trivial implementation is this:

unsigned GetLowestBitPos(unsigned value)
{
   assert(value != 0); // handled separately

   unsigned pos = 0;
   while (!(value & 1))
   {
      value >>= 1;
      ++pos;
   }
   return pos;
}

Any ideas how to squeeze some cycles out of it?

(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)

[edit] Thanks everyone for the ideas! I've learnt a few other things, too. Cool!

© Stack Overflow or respective owner

Related posts about c

    Related posts about c++