bitwise most significant set bit

后端 未结 10 1972
走了就别回头了
走了就别回头了 2020-12-20 19:50

I want to find the most significant bit that is set to 1. I have tried every possible way from & to ORing all of the bits from 1 t

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 20:11

    The slickest implementation I've come across - three iterations and a table lookup.

    unsigned int msb32(unsigned int x)
    {
        static const unsigned int bval[] =
        { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
    
        unsigned int base = 0;
        if (x & 0xFFFF0000) { base += 32/2; x >>= 32/2; }
        if (x & 0x0000FF00) { base += 32/4; x >>= 32/4; }
        if (x & 0x000000F0) { base += 32/8; x >>= 32/8; }
        return base + bval[x];
    }
    

提交回复
热议问题