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

后端 未结 27 3104
终归单人心
终归单人心 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:18

    I assume your question is for an integer (called v below) and not an unsigned integer.

    int v = 612635685; // whatever value you wish
    
    unsigned int get_msb(int v)
    {
        int r = 31;                         // maximum number of iteration until integer has been totally left shifted out, considering that first bit is index 0. Also we could use (sizeof(int)) << 3 - 1 instead of 31 to make it work on any platform.
    
        while (!(v & 0x80000000) && r--) {   // mask of the highest bit
            v <<= 1;                        // multiply integer by 2.
        }
        return r;                           // will even return -1 if no bit was set, allowing error catch
    }
    

    If you want to make it work without taking into account the sign you can add an extra 'v <<= 1;' before the loop (and change r value to 30 accordingly). Please let me know if I forgot anything. I haven't tested it but it should work just fine.

提交回复
热议问题