What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

后端 未结 27 3299
终归单人心
终归单人心 2020-11-22 03:35

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of

27条回答
  •  感动是毒
    2020-11-22 04:17

    thats some kind of binary search, it works with all kinds of (unsigned!) integer types

    #include 
    #define UINT (unsigned int)
    #define UINT_BIT (CHAR_BIT*sizeof(UINT))
    
    int msb(UINT x)
    {
        if(0 == x)
            return -1;
    
        int c = 0;
    
        for(UINT i=UINT_BIT>>1; 0>=1)
        if(static_cast(x >> i))
        {
            x >>= i;
            c |= i;
        }
    
        return c;
    }
    

    to make complete:

    #include 
    #define UINT unsigned int
    #define UINT_BIT (CHAR_BIT*sizeof(UINT))
    
    int lsb(UINT x)
    {
        if(0 == x)
            return -1;
    
        int c = UINT_BIT-1;
    
        for(UINT i=UINT_BIT>>1; 0>=1)
        if(static_cast(x << i))
        {
            x <<= i;
            c ^= i;
        }
    
        return c;
    }
    

提交回复
热议问题