Rust program to print the bit positions that need to be flipped to convert a number to another number

Given two integer numbers, write a Rust program to print the bit positions that need to be flipped to convert a given number (first number) to another number (second number).
Submitted by Nidhi, on September 25, 2021

Problem Solution:

Here, we will create two 32-bit integer numbers and then we will read numbers from the user and print the bit positions, that need to be flipped to convert the first number to the second number.

Program/Source Code:

The source code to print the bits to be flipped to convert a number to another number is given below. The given program is compiled and executed successfully.

// Rust program to print the bits to be flipped 
// to convert a number to another number

use std::io;

fn main() {
    let mut num1:i32 = 0;
    let mut num2:i32 = 0;
    let mut lsb1:i32 = 0;
    let mut lsb2:i32 = 0;
    let mut bitNum:i32 = 0;
    
    let mut input1 = String::new();
    let mut input2 = String::new();
    
    println!("Enter number1: ");
    io::stdin().read_line(&mut input1).expect("Not a valid string");
    num1 = input1.trim().parse().expect("Not a valid number");

    println!("Enter number2: ");
    io::stdin().read_line(&mut input2).expect("Not a valid string");
    num2 = input2.trim().parse().expect("Not a valid number");

    println!("Num1: {}",num1);
    println!("Num2: {}",num2);
 
    println!("Flipped bits positions:");
    while (num1 > 0) || (num2 > 0) 
    {
        lsb1 = num1 & 1;
        lsb2 = num2 & 1;

        if lsb1 != lsb2
        {
            print!("{} ", bitNum);
        }

        num1 = num1 >> 1;
        num2 = num2 >> 1;
        
        bitNum=bitNum+1;
    }   
}

Output:

RUN 1:
Enter number1: 
4
Enter number2: 
7
Num1: 4
Num2: 7
Flipped bits positions:
0 1 

RUN 2:
Enter number1: 
16
Enter number2: 
255
Num1: 16
Num2: 255
Flipped bits positions:
0 1 2 3 5 6 7

RUN 3:
Enter number1: 
16
Enter number2: 
16
Num1: 16
Num2: 16
Flipped bits positions:

Explanation:

Here, we created two integer variables num1, num2 with an initial value of 0. Then we read the value of variables from the user. After that, we print the bit positions that need to be flipped to convert the first number to the second number and print the result.

Rust Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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