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

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

    Here is a fast solution for C that works in GCC and Clang; ready to be copied and pasted.

    #include 
    
    unsigned int fls(const unsigned int value)
    {
        return (unsigned int)1 << ((sizeof(unsigned int) * CHAR_BIT) - __builtin_clz(value) - 1);
    }
    
    unsigned long flsl(const unsigned long value)
    {
        return (unsigned long)1 << ((sizeof(unsigned long) * CHAR_BIT) - __builtin_clzl(value) - 1);
    }
    
    unsigned long long flsll(const unsigned long long value)
    {
        return (unsigned long long)1 << ((sizeof(unsigned long long) * CHAR_BIT) - __builtin_clzll(value) - 1);
    }
    

    And a little improved version for C++.

    #include 
    
    constexpr unsigned int fls(const unsigned int value)
    {
        return (unsigned int)1 << ((sizeof(unsigned int) * CHAR_BIT) - __builtin_clz(value) - 1);
    }
    
    constexpr unsigned long fls(const unsigned long value)
    {
        return (unsigned long)1 << ((sizeof(unsigned long) * CHAR_BIT) - __builtin_clzl(value) - 1);
    }
    
    constexpr unsigned long long fls(const unsigned long long value)
    {
        return (unsigned long long)1 << ((sizeof(unsigned long long) * CHAR_BIT) - __builtin_clzll(value) - 1);
    }
    

    The code assumes that value won't be 0. If you want to allow 0, you need to modify it.

提交回复
热议问题