How to use bitset with _Find_first() and _Find_next() to find set bits indexes in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>

int main() {
    // Create a 16-bit bitset initialized to all 0
    std::bitset<16> bs;

    // Set specific bits at positions 3, 5, 11, and 14 to 1
    bs[3] = bs[5] = bs[11] = bs[14] = 1;

    // Print the entire bitset (from highest to lowest bit)
    std::cout << std::bitset<16>(bs) << std::endl;

    // Find and print the index of the first set bit (least significant bit that is 1)
    std::cout << "First set bit at index: " << bs._Find_first() << std::endl;

    // Print all indexes of bits that are set to 1
    std::cout << "All the set bits indexes: " << std::endl;

    // Iterate through all set bits using _Find_first and _Find_next
    for (int i = bs._Find_first(); i < bs.size(); i = bs._Find_next(i)) {
        std::cout << i << " ";
    }
}



/*
run:

0100100000101000
First set bit at index: 3
All the set bits indexes: 
3 5 11 14 

*/

 



answered Nov 3 by avibootz
...