ADVERTISEMENT
ADVERTISEMENT

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 »



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.