Q:

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

belongs to collection: Rust Basic Programs

0

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.

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 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 numpos1pos2 that are initialized with 428, 4, 7 respectively. Then we exchanged the bits of the given number and printed the updated number.

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 check a given number is the power ... >>
<< Rust program to read a number and print bits betwe...