Q:

Rust program to get the minimum number of bits to store a number

belongs to collection: Rust Basic Programs

0

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

// Rust program to get minimum number 
// of bits to store a number

fn main() {
    let mut num:i16 = 14;
    let mut val:i16 = 15;
    let mut cnt:i16 = 0;
    let mut tmp:i16 = 0;
    
    while val>=0
    {
        tmp = num & (1<<val);
        if tmp>0
        {
            cnt = cnt + 1;
        }
        val = val - 1;
    }

    if(num!=0)
    {
        cnt=cnt+1;
    }

    println!("Total number of bits required = {}",cnt);
}

Output:

Total number of bits required = 4

Explanation:

Here, we created an integer variable num with an initial value of 14. Then we checked the bits to get the minimum number of bits are required to store a number 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 check specific bit is HIGH (1) or ... >>
<< Rust program to convert a decimal number to a bina...