Rust program to find the 1's complement of the given number

Given a number, write a Rust program to find the 1's complement of the given number.
Submitted by Nidhi, on September 26, 2021

Problem Solution:

Here, we will create an 8-bit integer number and then we will find the 1's complement of the given number and printed the result.

Program/Source Code:

The source code to find the 1's complement of the given number is given below. The given program is compiled and executed successfully.

// Rust program to find the 1's complement 
// of given number

fn main(){
    let mut num:i8 = 9;
    let mut cnt:i8 = 7;
    let mut tmp:i8 = 0;
    let mut flg:i8 = 0;
    
    println!("Binary number: {:#0b}",num);
    
    while cnt >= 0 
    {
        tmp = num & (1 << cnt);
        if tmp>0
        {
            flg=1;
            num &= !(1<<cnt);
        }
        else
        {
            if(flg==1)
            {
                num |= (1<<cnt);
            }
        }
        cnt=cnt-1;
    }
    
    println!("1's complement of number: {:#0b}",num);
}

Output:

Binary number: 0b1001
1's complement of number: 0b110

Explanation:

Here, we created an integer variable num with an initial value of 9. Then we found the 1's complement of the given number and printed the result.

Rust Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.