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

Here, we are going to learn how to swap two numbers using bitwise XOR (^) operator in Rust programming language?
Submitted by Nidhi, on September 23, 2021

Problem Solution:

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.

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 num1, num2 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.

Rust Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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