Search code examples
c++bit-manipulationbit

Return bit positions without loops


Is there any way of finding bit positions without using loops (for/while) in C++, using std::bitset? Suppose we have a binary number 11001 and we'd like to find all 0s positions. Any sort of prebuilt, time-space efficient functions?


Solution

  • without using loops

    we have a binary number 11001 and we'd like to find all 0s positions

    Unroll the loop yourself.

    void check(unsigned pos, unsigned number, std::vector<unsigned>& out) {
        if (!(number & (1u << pos))) out.push_back(pos);
    }
    std::vector<unsigned> positions_of_0s(unsigned number) {
        std::vector<unsigned> ret;
        check(0, number, ret);
        check(1, number, ret);
        check(2, number, ret);
        check(3, number, ret);
        check(4, number, ret);
        return ret;
    }