Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to find the Nth set bit in a 32‑bit integer with C++

1 Answer

0 votes
#include <iostream>
#include <cstdint>
#include <bitset>
 
/*
    findNthSetBit32:
    ----------------
    Given:
        - x : a 32-bit integer
        - n : which set bit to find (1-based index)
 
    Returns:
        A 32-bit mask with ONLY the Nth set bit of x turned on.
        If n is larger than the number of set bits, returns 0.
 
    Algorithm:
        - Use std::countr_zero to locate the lowest set bit.
        - Remove that bit using x &= (x - 1).
        - When we reach the Nth one, return 1u << index.
*/
// Find the Nth set bit (1-based) in a 32-bit integer.
// Returns a mask with ONLY that bit set, or 0 if not enough bits.
std::uint32_t findNthSetBit32(std::uint32_t x, unsigned n)
{
    // Loop while there are still set bits remaining in x
    while (x != 0) {
 
        // std::countr_zero(x) returns the number of trailing zeros,
        // which is the index (0–31) of the lowest set bit.
        unsigned index = std::countr_zero(x);
 
        // Decrement n; if this was the Nth set bit, return a mask
        // with ONLY that bit set: (1 << index)
        if (--n == 0)
            return 1u << index;
 
        // Remove the lowest set bit from x.
        // Trick: x & (x - 1) clears the least significant 1-bit.
        x &= (x - 1);
    }
 
    // If we exit the loop, x had fewer than n set bits.
    return 0;
}
 
int main()
{
    std::uint32_t value =
        0b00001101001101101100100010100000u;
 
    unsigned n = 4;
 
    std::uint32_t result = findNthSetBit32(value, n);
 
    std::cout << "Input value:  " << std::bitset<32>(value) << "\n";
    std::cout << "N = " << n << "\n";
    std::cout << "Result mask:  " << std::bitset<32>(result) << "\n";
}
 
 
/*
run:
 
Input value:  00001101001101101100100010100000
N = 4
Result mask:  00000000000000000100000000000000
 
*/

 



answered Jul 24 by avibootz
edited Jul 24 by avibootz
...