Rust program to swap two bits of a 32-bit integer number

Given an integer number, write a Rust program to swap two bits of a 32-bit integer number.
Submitted by Nidhi, on September 25, 2021

Problem Solution:

Here, we will create a 32-bit integer number and then we will swap the 4th and 7th bits of a given number using a bitwise operator and printed the result.

Program/Source Code:

The source code to swap two bits of a 32-bit integer number is given below. The given program is compiled and executed successfully.

// Rust program to swap two bits 
// of a 32-bit integer number

fn main() {
    let mut num:i32 = 428;
    let mut pos1:i32 = 4;
    let mut pos2:i32 = 7;
    
    println!("Binary number before swapping bits: {:#02b}",num);
    
    num = num ^ (1 << pos1);
    num = num ^ (1 << pos2);
    
    println!("Binary number after swapping bits: {:#02b}",num);
}

Output:

Binary number before swapping bits: 0b110101100
Binary number after swapping bits: 0b100111100

Explanation:

Here, we created three integer variables num, pos1, pos2 that are initialized with 428, 4, 7 respectively. Then we exchanged the bits of the given number and printed the updated number.

Rust Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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