Q:

Rust program to reverse bits of a binary number

belongs to collection: Rust Basic Programs

0

Here, we will create a 16-bit integer number and then we will reverse the bits of the given number and print 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 reverse bits of a binary number is given below. The given program is compiled and executed successfully.

// Rust program to reversing bits 
// of a binary number

fn main()
{
    let mut num:u16 = 11;
    let mut val:u16 = 0;
    let mut tmp:u16 = 0;
    let mut rev:u16 = 0;
    
    println!("Binary number is: {:#0b}", num);
	
    while val < 16 
    {
        tmp = num & (1 << val);
        if tmp>0
        {
            rev = rev | (1 << ((16 - 1) - val));
        }
        val = val + 1;
    }
    println!("Reversed binary number is: {:#0b}", rev);
}

Output:

Binary number is: 0b1011
Reversed binary number is: 0b1101000000000000

Explanation:

Here, we created a 16-bit integer variable num with an initial value of 11. Then we reversed the bits of a given number using bitwise operators and printed the result.

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 count the total number of HIGH (1)... >>
<< Rust program to swap two bytes of a number...