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 64‑bit integer with JavaScript

1 Answer

0 votes
/*
    countTrailingZeros:
    -------------------
    Returns the number of trailing zeros in a 64‑bit integer (BigInt).
    Equivalent to C++ std::countr_zero or GCC __builtin_ctzll.

    Algorithm:
        - Isolate lowest set bit: x & -x
        - Its index is log2(lowest_bit)
*/
function countTrailingZeros(x) {
    const lowest = x & -x;                 // isolate lowest set bit
    
    return Math.log2(Number(lowest));      // index (0–63)
}

/*
    findNthSetBit64:
    ----------------
    Given:
        - x : a 64-bit integer (BigInt)
        - n : which set bit to find (1-based index)

    Returns:
        A 64-bit mask (BigInt) with ONLY the Nth set bit of x turned on.
        If n is larger than the number of set bits, returns 0n.

    Algorithm:
        - Use countTrailingZeros(x) to locate the lowest set bit.
        - Remove that bit using x &= (x - 1n).
        - When we reach the Nth one, return 1n << index.
*/
function findNthSetBit64(x, n) {
    while (x !== 0n) {

        const index = countTrailingZeros(x);

        n -= 1;
        if (n === 0) {
            return 1n << BigInt(index);
        }

        // Remove the lowest set bit
        x &= (x - 1n);
    }

    return 0n;
}

/*
    toBinary64:
    -----------
    Convert BigInt to a padded 64-bit binary string.
*/
function toBinary64(x) {
    const s = x.toString(2);
    return s.padStart(64, "0");
}


// --------------------
// Main 
// --------------------

const value =
    0b0000000000000000000010000000000000001101001101101100100010100000n;

const n = 4;

const result = findNthSetBit64(value, n);

console.log("Input value:  ", toBinary64(value));
console.log("N =", n);
console.log("Result mask:  ", toBinary64(result));



/*
run:

Input value:   0000000000000000000010000000000000001101001101101100100010100000
N = 4
Result mask:   0000000000000000000000000000000000000000000000000100000000000000

*/

 



answered Jul 25 by avibootz
...