Q:

Rust program to find the position of MSB bit of an integer number

belongs to collection: Rust Basic Programs

0

Here, we will create a 32-bit integer number and then we will read the number from the user and find the position of MSB bit of an integer number using bitwise operators.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to find the position of the MSB bit of an integer number is given below. The given program is compiled and executed successfully.

// Rust program to find the position of 
// MSB bit of an integer number

use std::io;

fn main() {
    let mut num:i32 = 0;
    let mut cnt:u32 = 0;
    let mut input = String::new();
    
    println!("Enter number: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    num = input.trim().parse().expect("Not a valid number");

    println!("Binary number: {:#02b}",num);
    
    while num>0 
    {
        cnt=cnt+1;
        num = num >> 1;
    }

    println!("MSB position is: {}",cnt-1);
}

Output:

RUN 1:
Enter number: 
9
Binary number: 0b1001
MSB position is: 3

RUN 2:
Enter number: 
255
Binary number: 0b11111111
MSB position is: 7

Explanation:

Here, we created an integer variable num with an initial value of 0. Then we read the value of the number from the user and found the position of the MSB bit and printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to round off an integer number to the... >>
<< Rust program to find the next number power of 2...