Position of least significant bit that is set

后端 未结 23 1442
时光取名叫无心
时光取名叫无心 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 08:59

    The fastest (non-intrinsic/non-assembler) solution to this is to find the lowest-byte and then use that byte in a 256-entry lookup table. This gives you a worst-case performance of four conditional instructions and a best-case of 1. Not only is this the least amount of instructions, but the least amount of branches which is super-important on modern hardware.

    Your table (256 8-bit entries) should contain the index of the LSB for each number in the range 0-255. You check each byte of your value and find the lowest non-zero byte, then use this value to lookup the real index.

    This does require 256-bytes of memory, but if the speed of this function is so important then that 256-bytes is well worth it,

    E.g.

    byte lowestBitTable[256] = {
    .... // left as an exercise for the reader to generate
    };
    
    unsigned GetLowestBitPos(unsigned value)
    {
      // note that order to check indices will depend whether you are on a big 
      // or little endian machine. This is for little-endian
      byte* bytes = (byte*)value;
      if (bytes[0])
        return lowestBitTable[bytes[0]];
      else if (bytes[1])
          return lowestBitTable[bytes[1]] + 8;
      else if (bytes[2])
          return lowestBitTable[bytes[2]] + 16;
      else
          return lowestBitTable[bytes[3]] + 24;  
    }
    

提交回复
热议问题