Integer Bit Width And Log2

Count set bits, measure leading zeros, and round up with next_power_of_two while walking u32 bit positions and rotates.

RustData Integrity

Code

rustsnippet
24 lines
fn main() {
    let value: u32 = 0b0000_0000_0000_0000_0010_1100_1010_0100;

    // count_ones counts set bits, leading_zeros measures the unused high bits
    println!("count_ones: {}", value.count_ones());
    println!("leading_zeros: {}", value.leading_zeros());
    println!("trailing_zeros: {}", value.trailing_zeros());
    println!("bit width: {}", u32::BITS - value.leading_zeros());

    // ilog2 returns the zero-based position of the highest set bit
    println!("ilog2: {}", value.ilog2());
    println!("same as 31 minus leading zeros: {}", 31 - value.leading_zeros());

    // next_power_of_two rounds up to a power of two bound
    println!("next_power_of_two: {}", value.next_power_of_two());
    println!("is_power_of_two: {}", value.is_power_of_two());

    for shift in 0..4 {
        println!("bit {shift}: {}", (value >> shift) & 1);
    }

    // rotate_left keeps every bit while moving positions
    println!("rotated: {:#034b}", value.rotate_left(8));
}

How the snippet works

Integer Bit Width And Log2 comes down to the function main.

Repetition is confined to for shift in 0..4 — the rest of the file is straight-line.

Applying it

The run emits 10 labeled sections — count_ones:, leading_zeros:, trailing_zeros:, bit width:, ilog2:, same as 31 minus leading zeros:, next_power_of_two:, is_power_of_two:, bit, rotated: — one per step.

Statements that matter

let value: u32 = 0b0000_0000_0000_0000_0010_1100_1010_0100;

Interactive Tools for This Topic

FAQ

What does Integer Bit Width And Log2 print when run?
Execute the whole file; each printed line is prefixed with a label like `count_ones:`, `leading_zeros:`, `trailing_zeros:`.