Position of least significant bit that is set

后端 未结 23 1274
时光取名叫无心
时光取名叫无心 2020-11-22 08:46

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 impleme

23条回答
  •  余生分开走
    2020-11-22 09:09

    If you have the resources, you can sacrifice memory in order to improve the speed:

    static const unsigned bitPositions[MAX_INT] = { 0, 0, 1, 0, 2, /* ... */ };
    
    unsigned GetLowestBitPos(unsigned value)
    {
        assert(value != 0); // handled separately
        return bitPositions[value];
    }
    

    Note: This table would consume at least 4 GB (16 GB if we leave the return type as unsigned). This is an example of trading one limited resource (RAM) for another (execution speed).

    If your function needs to remain portable and run as fast as possible at any cost, this would be the way to go. In most real-world applications, a 4GB table is unrealistic.

提交回复
热议问题