Position of least significant bit that is set

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

    Another method (modulus division and lookup) deserves a special mention here from the same link provided by @anton-tykhyy. this method is very similar in performance to DeBruijn multiply and lookup method with a slight but important difference.

    modulus division and lookup

     unsigned int v;  // find the number of trailing zeros in v
        int r;           // put the result in r
        static const int Mod37BitPosition[] = // map a bit value mod 37 to its position
        {
          32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4,
          7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5,
          20, 8, 19, 18
        };
        r = Mod37BitPosition[(-v & v) % 37];
    

    modulus division and lookup method returns different values for v=0x00000000 and v=FFFFFFFF whereas DeBruijn multiply and lookup method returns zero on both inputs.

    test:-

    unsigned int n1=0x00000000, n2=0xFFFFFFFF;
    
    MultiplyDeBruijnBitPosition[((unsigned int )((n1 & -n1) * 0x077CB531U)) >> 27]); /* returns 0 */
    MultiplyDeBruijnBitPosition[((unsigned int )((n2 & -n2) * 0x077CB531U)) >> 27]); /* returns 0 */
    Mod37BitPosition[(((-(n1) & (n1))) % 37)]); /* returns 32 */
    Mod37BitPosition[(((-(n2) & (n2))) % 37)]); /* returns 0 */
    

提交回复
热议问题