Q:

Rust program to swap two numbers using bitwise XOR (^) operator

belongs to collection: Rust Basic Programs

0

Bitwise XOR (^): The bitwise XOR operator (^) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s.

Here, we will create two variables then we will swap the value of variables using the bitwise XOR (^) operator and print the updated value.

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 swap two numbers using the bitwise XOR (^) operator is given below. The given program is compiled and executed successfully.

// Rust program to swap two numbers 
// using bitwise XOR (^) operator

fn main() {
    let mut num1:i32 = 6;
    let mut num2:i32 = 2;
    
    println!("Numbers before swapping:");
    println!("\tNum1: {}",num1);
    println!("\tNum2: {}",num2);

    num1 = num1 ^ num2;
    num2 = num1 ^ num2;
    num1 = num1 ^ num2;

    println!("Numbers after swapping:");
    println!("\tNum1: {}",num1);
    println!("\tNum2: {}",num2);
}

Output:

Numbers before swapping:
        Num1: 6
        Num2: 2
Numbers after swapping:
        Num1: 2
        Num2: 6

Explanation:

Here, we created 2 integer variables num1num2 that are initialized with 6, 2 respectively. Then we exchanged values of both variables using the bitwise XOR (^) operator. After that, we printed the updated values.

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 set specific bit using bitwise ope... >>
<< Rust program to demonstrate the bitwise XOR (^) op...