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

1 Answer

0 votes
/*
    countTrailingZeros:
    -------------------
    Returns the number of trailing zeros in a 32‑bit integer.
    Equivalent to C++ std::countr_zero or GCC __builtin_ctz.

    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(lowest);     // index of that bit
}

/*
    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 countTrailingZeros(x) to locate the lowest set bit.
        - Remove that bit using x &= (x - 1).
        - When we reach the Nth one, return 1 << index.
*/
function findNthSetBit32(x, n) {
    while (x !== 0) {

        // Index (0–31) of the lowest set bit
        const index = countTrailingZeros(x);

        // If this is the Nth set bit, return mask
        if (--n === 0)
            return 1 << index;

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

    // Fewer than n set bits
    return 0;
}

/*
    toBinary32:
    -----------
    Convert integer to a padded 32-bit binary string.
*/
function toBinary32(x) {
    const s = (x >>> 0).toString(2);   // >>> 0 forces unsigned 32-bit
    
    return s.padStart(32, "0");
}


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

const value = 0b00001101001101101100100010100000;
const n = 4;

const result = findNthSetBit32(value, n);

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


/*
run:

Input value:   00001101001101101100100010100000
N = 4
Result mask:   00000000000000000100000000000000

*/

 



answered Jul 25 by avibootz
...