Q:

Rust program to count the total number of HIGH (1) bits a given binary number

0

Here, we will create a 16-bit integer number and then we will count the total HIGH (1) bits of the given number.

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 count the total number of bits are HIGH (1) in a given binary number is given below. The given program is compiled and executed successfully.

// Rust program to count total number of bits 
// are HIGH (1) in a given binary number

fn main() {
    let mut num:i16 = 14;
    let mut val:i16 = 15;
    let mut tmp:i16 = 0;
    let mut cnt:i16 = 0;
    
    println!("Decimal Number: {}",num);
    print!("Binary Number: ");
	
    while val>=0
    {
        tmp = num & (1<<val);
        if tmp>0
        {
            print!("1");
            cnt = cnt + 1;
        }
        else
        {
            print!("0");
        }
        val = val - 1;
    }
    println!("\nTotal HIGH bits are: {}",cnt);
}

Output:

Decimal Number: 14
Binary Number: 0000000000001110
Total HIGH bits are: 3

Explanation:

Here, we created a 16-bit integer variable num with an initial value of 14. Then we counted the total HIGH (1) 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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now