---
title: "Create a function to convert a decimal number to binary using Rust."  
description: "Create a function to convert a decimal number to binary using Rust."  
author: "Utpal Vishwas"  
published: 2023-06-22  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158831/create-a-function-to-convert-a-decimal-number-to-binary-using-rust  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Create a function to convert a decimal number to binary using Rust.

Create a [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to [convert](https://www.mindstick.com/forum/2093/configurationmanager-appsettings-convert-n-to-n-why) a [decimal](https://www.mindstick.com/forum/34709/please-write-a-program-for-decimal-to-binary-conversion-in-c-sharp) number to binary using Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust function to convert a decimal number to binary using Rust:

Rust

```plaintext
fn decimal_to_binary(number: i32) -> String {
    let mut binary_string = String::new();
    let mut remainder = number;
    while remainder > 0 {
        let digit = remainder % 2;
        binary_string.push(char::from_digit(digit, 10));
        remainder = remainder / 2;
    }
    binary_string.reverse();
    return binary_string;
}

fn main() {
    let number = 10;
    let binary_number = decimal_to_binary(number);
    println!("The binary representation of {} is {}", number, binary_number);
}
```

This function first defines a function called decimal_to_binary that takes an i32 number as input and returns a String. The function first initializes a variable called binary_string to an empty string. Then, the function iterates through the number, dividing the number by 2 and adding the remainder to the binary_string. Finally, the function reverses the binary_string and returns it.

The main function of the program then calls the decimal_to_binary function with the value 10 as input. The result of the function call is then printed to the console.

To run the program, you can save it as a file called decimal_to_binary.rs and then compile it using the following command:

Code snippet

```plaintext
rustc decimal_to_binary.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./decimal_to_binary
```

This will print the following output to the console:

Code snippet

```plaintext
The binary representation of 10 is 1010
```


---

Original Source: https://www.mindstick.com/forum/158831/create-a-function-to-convert-a-decimal-number-to-binary-using-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
