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

1 Answer

0 votes
import Foundation

/*
    findNthSetBit32:
    ----------------
    Given:
        - x : a 32-bit unsigned integer (UInt32)
        - 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 x.trailingZeroBitCount to locate the lowest set bit.
        - Remove that bit using x &= (x &- 1).
        - When we reach the Nth one, return 1 << index.

    Notes:
        - trailingZeroBitCount maps to a single CPU instruction.
        - Swift's UInt32 is a true 32-bit unsigned integer.
*/
func findNthSetBit32(_ x0: UInt32, _ n0: UInt32) -> UInt32 {
    var x = x0
    var n = n0

    while x != 0 {
        // Index (0–31) of the lowest set bit
        let index = x.trailingZeroBitCount

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

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

    // Fewer than n set bits
    return 0
}

/*
    toBinary32:
    -----------
    Convert UInt32 to a padded 32-bit binary string.
*/
func toBinary32(_ x: UInt32) -> String {
    let s = String(x, radix: 2)
    return String(repeating: "0", count: 32 - s.count) + s
}

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

let value: UInt32 = 0b00001101001101101100100010100000
let n: UInt32 = 4

let result = findNthSetBit32(value, n)

print("Input value:  \(toBinary32(value))")
print("N = \(n)")
print("Result mask:  \(toBinary32(result))")



/*
run:

Input value:  00001101001101101100100010100000
N = 4
Result mask:  00000000000000000100000000000000

*/

 



answered Jul 25 by avibootz
...