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

1 Answer

0 votes
"""
    find_nth_set_bit32:
    -------------------
    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 count_trailing_zeros(x) to locate the lowest set bit.
        - Remove that bit using x &= (x - 1).
        - When we reach the Nth one, return 1 << index.
"""

def count_trailing_zeros(x: int) -> int:
    """
    Count 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 the bit_length of that isolated bit minus 1
    """
    lowest_bit = x & -x

    return lowest_bit.bit_length() - 1


def find_nth_set_bit32(x: int, n: int) -> int:
    """
    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.
    """
    while x != 0:

        # Index (0–31) of the lowest set bit
        index = count_trailing_zeros(x)

        # If this is the Nth set bit, return mask
        n -= 1
        if n == 0:
            return 1 << index

        # Remove the lowest set bit
        x &= (x - 1)

    # Fewer than n set bits
    return 0


def to_binary32(x: int) -> str:
    """Convert integer to a padded 32-bit binary string."""
    s = bin(x)[2:]
    return s.zfill(32)


def main():
    value = 0b00001101001101101100100010100000
    n = 4

    result = find_nth_set_bit32(value, n)

    print("Input value:  ", to_binary32(value))
    print("N =", n)
    print("Result mask:  ", to_binary32(result))


if __name__ == "__main__":
    main()


"""
run:

Input value:   00001101001101101100100010100000
N = 4
Result mask:   00000000000000000100000000000000

"""

 



answered Jul 25 by avibootz
...