Rust program to reverse bits of a binary number

Here, we are going to learn how to reverse bits of a binary 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 reverse the bits of the given number and print the result.

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);


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


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.

Rust Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.