ADVERTISEMENT
ADVERTISEMENT

Rust program to convert a decimal number to a binary number

Here, we are going to learn how to convert a decimal number to a binary number in Rust programming language?
Submitted by Nidhi, on September 24, 2021

Problem Solution:

Here, we will create a 16-bit integer number and then print the corresponding binary number.

Program/Source Code:

The source code to convert a decimal number to a binary number is given below. The given program is compiled and executed successfully.

// Rust program to convert decimal number 
// to binary number

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

Output:

Decimal Number: 14
Binary Number: 0000000000001110

Explanation:

Here, we created an integer variable num with an initial value of 14. Then we used bitwise operators to print the corresponding binary number.

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.