Home »
Rust »
Rust Programs
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.
Last Updated : September 26, 2021
Problem Statement
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