/*
find_nth_set_bit32:
-------------------
Given:
- x : a 32-bit unsigned integer (u32)
- 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.trailing_zeros() to locate the lowest set bit.
- Remove that bit using x &= x - 1.
- When we reach the Nth one, return 1 << index.
Notes:
- trailing_zeros() maps to a single CPU instruction.
- Rust's u32 is a true 32-bit unsigned integer.
*/
fn find_nth_set_bit32(mut x: u32, mut n: u32) -> u32 {
while x != 0 {
// Index (0–31) of the lowest set bit
let index: u32 = x.trailing_zeros();
// If this is the Nth set bit, return mask
n -= 1;
if n == 0 {
return 1u32 << index;
}
// Remove the lowest set bit
x &= x - 1;
}
// Fewer than n set bits
0
}
/*
to_binary32:
-----------
Convert a u32 to a padded 32-bit binary string.
*/
fn to_binary32(x: u32) -> String {
format!("{:032b}", x)
}
fn main() {
let value: u32 = 0b00001101001101101100100010100000;
let n: u32 = 4;
let result: u32 = find_nth_set_bit32(value, n);
println!("Input value: {}", to_binary32(value));
println!("N = {}", n);
println!("Result mask: {}", to_binary32(result));
}
/*
run:
Input value: 00001101001101101100100010100000
N = 4
Result mask: 00000000000000000100000000000000
*/