Search code examples
c++mathbinaryinteger

Finding\pointing to the leftmost set bit in a binary integer


Given x, a binary integer, y = x & (~x + 1) points to the rightmost set bit. For example:

x = 0000101101011000
y = 0000000000001000

Now my question is: Can we find a bitwise formula to point to the leftmost set bit? For example:

x = 0000101101011000
y = 0000100000000000

Any idea will be appreciated.


Solution

  • I have found a solution here on java

    https://codeforces.com/blog/entry/10330

    seems like java supports it out of the box I don't know if its implemented in C++ standard library but I could translate it into C++

    code in C++ is the following:

    #include <iostream>
    #include <bitset>
    
    
    int highestOneBit(int i) {
        i |= (i >>  1);
        i |= (i >>  2);
        i |= (i >>  4);
        i |= (i >>  8);
        i |= (i >> 16);
        return i - ((unsigned int)i >> 1);
    }
    
    int main()
    {
        int x = 951;    
        std::cout << std::bitset<sizeof(int) * 8>(x) << std::endl;
        std::cout << std::bitset<sizeof(int) * 8>(highestOneBit(x)) << std::endl;
        return 0;
    }