Skip to main content
  1. Posts/

Decimal to Binary in Rust

·1054 words·5 mins

Hello, it’s been a long time since I published my last blog. So in honorary of my return, I decided to create a opposing program for my python version. Instead using rust (although it’s still pretty hard in my opinion!). I decided to create a rust program that converts a decimal number (a normal number) to a binary number (using base 2: 0 or 1). I will provide steps and tips along the way. :)))

STEP 1: Create a new rust file using cargo #

Before we get into all that programming and technical stuff, we need to create a file. To do that, we can use cargo. cargo is a tool designed for rust, it can help create a skeleton file, compile/build your program, run it etc. Here’s the steps:

  1. First go to your rust folder/directory
PS C:\Users\kodert> cd dev
PS C:\Users\kodert\dev> cd rust
PS C:\Users\kodert\dev\rust> eza
convert_celsius_to_fahrenheit  faces        hey      temp
dec_to_bin                     hello_world  hi_name
PS C:\Users\kodert\dev\rust>
  1. Run cargo new [desired name]
PS C:\Users\kodert\dev\rust> cargo new [desired name]
  1. Open your text editor
PS C:\Users\kodert\dev\rust> code .
  1. Finally, if you want to run your code: cargo run
# automatically compiles it for you :)
PS C:\Users\kodert\dev\rust> cargo run

Step 2: The plan #

In this program, I struggled to write the code because I didn’t have a strong foundation or a general plan in my head of how things were going to work. Let’s create a plan to prevent my rookie mistakes.

1. How do we even convert decimal number to binary? #

After two days of investigations, I found out a simple way to convert decimal to binary. The formula was: the decimal number divided by 2(because it’s based on the power of 2) and whatever the remainder was (0 or 1) was appended to the end of the number, then taking the result and repeating it again simple adding the remainded infront of the previous one. Here’s a simple diagram that better explains this:

Decimal to Binary diagram

2. What are the functions we will use? #

Well congrats on the first step of the plan! :) The next question we should ask ourselves is, what type of functions should we use? If you think deeper, we need to repeat the formula until the result or the quotient hits 0. Wait… Doesn’t that sounds like a farmiliar function? Does it ring the bell? While loop! It’s perfect for the job, it loops until the test conditions are met. What else… Maybe a function? To you know… Solve the problem using our new formula. That’s what we need. Oh. We are also missing something! Something that converts a string to integer because for some reason the commandline’s input is a string… We also need that. But don’t fret too much because we’re going to start with the basic fundamentals and then incorporate all the other things.

3. The code (brief summary) #

Let’s start doing this! First, let’s just create a program where we make the new function. Using fn [function name]([Parameter name] : [Type]) -> [The Type the function returns]{} then we will use the while loop to loop until the decimal number hits 0. Because if it doesn’t it will keep dividing the number by 2. We should then create a new mutable variables using let mut [variable name] for the remainder than we can use our parameter name and overwrite it so it takes the new result. The loop will check the conditions again does the parameter = 0 no then it will continue. However the remainder has nowhere to go, that’s why we will create an empty string for the remainder to append itself using a method. When we call our function in the main function, we set the parameter to 0 what will happen? Well it won’t work. We need to check ‘if’ the decimal number is 0 return 0.

Now we completed our main goal! Yipee!! Next we should create an input so that the user can type in a decimal number. I have a code on how to make an input here it is: input. There’s a massive problem actually two but let’s solve the main one first. You see I learn’t the hard way that the input from the commandline is really just a string, even if you type an integer! So let’s use this function called parse and match using the match this checks if the result is either ‘OK’ or ‘Err’. Parse converts something into a different Type. Lastly, let’s make the input on the same line as running the program name e.g: cargo run --[number]. To solve this let’s use a list or in rust terms a vector, which only contains string because of the commandline. We will capture the input of the second item excluding the program name aka the cargo run, then create a new variable. Assigning the index 1, item from the list to the new variable which we will parse. Use the variable from the ‘OK’, and use it as a parameter of our conversion function containg the input when we call our conversion function. THE END!!!!

YOU SUCCESFULLY CREATED YOUR VERY DECIMAL TO BINAY PROGRAM IN RUST!!!!! Here’s the code to compare or copy:

//use a std libary for the list called args
use std::env;

fn main() {
    //creates a list that accepts only string called args, the (env::args() and .collect(); )
    let args: Vec<String> = env::args().collect();

    if args.len() > 1 {
        let input_value = &args[1];
        //input_value.to_string();
        //convert the input_value from string to u64
        match input_value.parse::<u64>() {
            Ok(dec_num) => {
                println!("The input value is: {}", input_value);
                let bin_num = dec_to_bin(dec_num);
                println!("The binary number is: {bin_num}");
            }
            Err(error) => println!("error: {}", error),
        }
    } else {
        println!("No input value provided.")
    }

}

//the conversion function
fn dec_to_bin(dec_num: u64) -> String {
    if dec_num == 0 {
        return String::from("0");
    }

    let mut num = dec_num;
    let mut bin_str = String::new();

    while num > 0 {
        let remainder: u64 = num % 2;
        bin_str.insert_str(0, &remainder.to_string());

        num /= 2; //num = num / 2;
    }

    bin_str
}

Here is my draft that I did but wasn’t necessary in the final product:

    //DRAFT
    //let mut input = String::new();

    //std::io::stdin()
    //  .read_line(&mut input)
    //.expect("FAILED TO READ LINE!");

    //print!("input: {input}");

    //let trim_input = input_value.trim();

New leaving message. :))))

⠀⠀⠀⠀⣶⣄⠀⠀⠀⠀⠀⠀⢀⣶⡆⠀⠀⠀
⠀⠀⠀⢸⣿⣿⡆⠀⠀⠀⠀⢀⣾⣿⡇⠀⠀⠀
⠀⠀⠀⠘⣿⣿⣿⠀⠀⠀⠀⢸⣿⣿⡇⠀⠀⠀
⠀⠀⠀⠀⢿⣿⣿⣤⣤⣤⣤⣼⣿⡿⠃⠀⠀⠀
⠀⠀⠀⢠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠀⠀⠀
⠀⠀⢠⣿⡃⣦⢹⣿⣟⣙⣿⣿⠰⡀⣿⣇⠀⠀
⠠⠬⣿⣿⣷⣶⣿⣿⣿⣿⣿⣿⣷⣾⣿⣿⡭⠤
⠀⣼⣿⣿⣿⣿⠿⠛⠛⠛⠛⠻⢿⣿⣿⣿⣿⡀
⢰⣿⣿⣿⠋⠀⠀⠀⢀⣀⠀⠀⠀⠉⢿⣿⣿⣧
⢸⣿⣿⠃⠜⠛⠂⠀⠋⠉⠃⠐⠛⠻⠄⢿⣿⣿
⢸⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿
⠘⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⡏
⠀⠈⠻⠿⣤⣀⡀⠀⠀⠀⠀⠀⣀⣠⠾⠟⠋⠀

Bye for now!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!