ADVERTISEMENT
ADVERTISEMENT

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

Given a number, write a Rust program to find the 2'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 2's complement of the given number and printed the result.

Program/Source Code:

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

// Rust program to find the 2'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);
    println!("2's complement of number: {:#0b}",num+1);
}

Output:

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

Explanation:

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

Rust Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.