Q:

Rust program to read a number and print bits between given positions

belongs to collection: Rust Basic Programs

0

Here, we will create a 32-bit integer number and then we will print the binary number between two given positions.

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 read a number and print bits between given positions is given below. The given program is compiled and executed successfully.

// Rust program to read a number and 
// print bits between given positions

fn main() {
    let mut num:i32 = 428;
    let mut pos1:i32 = 4;
    let mut pos2:i32 = 7;
    let mut cnt:i32 = 0;
    let mut tmp:i32 = 0;
    
    println!("Binary number: {:#02b}",num);
    print!("Binary number between two positions: ");
	
    cnt=pos2;
	
    while cnt >= pos1 
    {
        tmp = num & (1 << cnt);
        if tmp>0
        {
            print!("1");
        }
        else
        {
            print!("0");
        }
        cnt=cnt-1;
    }
}

Output:

Binary number: 0b110101100
Binary number between two positions: 1010

Explanation:

Here, we created three integer variables numpos1pos2 that are initialized with 428, 4, 7 respectively. Then we printed the binary number between 4 to 7 positions.

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 swap two bits of a 32-bit integer ... >>
<< Rust program to find the total number of leading z...