Q:

Rust program to check a given number is the power of 2 using bitwise operator

belongs to collection: Rust Basic Programs

0

Here, we will create a 32-bit integer number and then we will read the number from the user and check the given number is the power of 2 using bitwise operators.

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 check a given number 
// is power of 2 using bitwise operator

use std::io;

fn main() {
    let mut num:i32 = 0;
    let mut input = String::new();
    
    println!("Enter number: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    num = input.trim().parse().expect("Not a valid number");

    if (num & (num - 1)) != 0
    {
        println!("Given number is not power of 2.");
    }
    else
    {
        println!("Given number is power of 2.");
    }
}

Output:

RUN 1:
Enter number: 
16
Given number is power of 2.

RUN 2:
Enter number: 
128
Given number is power of 2.

RUN 3:
Enter number: 
250
Given number is not power of 2.

Explanation:

Here, we created an integer variable num with the initial value of 0. Then we read the value of num from the user. After that, we checked the given number is a power of 2 or not and printed the appropriate message.

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 number of bits to be fli... >>
<< Rust program to swap two bits of a 32-bit integer ...