ADVERTISEMENT
ADVERTISEMENT

Rust program to swap two bytes of a number

Here, we are going to learn how to swap two bytes of a number in Rust programming language?
Submitted by Nidhi, on September 24, 2021

Problem Solution:

Here, we will create a 16-bit integer number and then we will swap bytes of the given number and print the result.

Program/Source Code:

The source code to swap two bytes of a number is given below. The given program is compiled and executed successfully.

// Rust program to swap two bytes of a number.

fn main()
{
    let mut num:u16 = 0x1234;

    println!("Number before swapping bytes is: {:#02x}", num);
    
    num = ((num << 8) & 0xff00) | ((num >> 8) & 0x00ff);
    
    println!("Number after swapping bytes is: {:#02x}", num);
}

Output:

Number before swapping bytes is: 0x1234
Number after swapping bytes is: 0x3412

Explanation:

Here, we created a 16-bit integer variable num with an initial value of 0x1234. Then we swapped bytes of the number using bitwise operators and printed the result.

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.