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

Here, we are going to learn how to find the position of MSB bit of an integer number in Rust programming language?
Submitted by Nidhi, on September 25, 2021

Problem Solution:

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.

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.

Rust Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.