ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.