Rust Program to Convert Decimal to Binary (Using Bitwise, Loop, Recursion, and More)
Introduction
Rust is a modern systems programming language that emphasizes performance, memory safety, and concurrency.
While it’s widely used for low-level development, Rust can also be leveraged for data conversion tasks like decimal to binary conversion with multiple approaches — bitwise operations, recursion, and loop-based methods.
Problem Statement
Write multiple Rust programs to convert decimal numbers into binary using various methods such as bitwise manipulation, while loops, recursion, and more.
Use Cases
-
Binary data handling in embedded systems.
-
Performing low-level data transformations.
-
Learning bitwise operations and memory-efficient logic.
-
Creating console tools for educational or debugging purposes.
Method 1: Using Bitwise Operator
// Program 1: Convert Decimal to Binary using Bitwise Operator
fn bitwise_binary(mut num: u32) -> String {
let mut result = String::new();
let mut started = false;
for i in (0..32).rev() {
let bit = (num >> i) & 1;
if bit == 1 {
started = true;
}
if started {
result.push_str(&bit.to_string());
}
}
if result.is_empty() {
result.push('0');
}
result
}
fn main() {
println!("Binary (45): {}", bitwise_binary(45));
}
Output
Binary (45): 101101
Explanation
-
Shifts bits from the highest to the lowest.
-
Starts appending bits when the first
1
is encountered.
Method 2: Using Recursion
// Program 2: Convert Decimal to Binary using Recursion
fn recursive_binary(num: u32) -> String {
if num == 0 {
return "".to_string();
}
let prev = recursive_binary(num / 2);
format!("{}{}", prev, num % 2)
}
fn main() {
let result = recursive_binary(18);
println!("Binary (18): {}", if result.is_empty() { "0".to_string() } else { result });
}
Output
Binary (18): 10010
Explanation
-
Recursively divides the number and builds the binary string.
-
Handles the base case for
0
.
Method 3: Using While Loop and Vec
// Program 3: Convert Decimal to Binary using While Loop
fn loop_binary(mut num: u32) -> String {
if num == 0 {
return "0".to_string();
}
let mut result = Vec::new();
while num > 0 {
result.push((num % 2).to_string());
num /= 2;
}
result.reverse();
result.join("")
}
fn main() {
println!("Binary (22): {}", loop_binary(22));
}
Output
Binary (22): 10110
Explanation
-
Collects binary digits in a vector.
-
Reverses them to get the correct order.
Method 4: Using Format Macro (Built-in)
// Program 4: Convert Decimal to Binary using Built-in format!
fn builtin_format(num: u32) -> String {
format!("{:b}", num)
}
fn main() {
println!("Binary (64): {}", builtin_format(64));
}
Output
Binary (64): 1000000
Explanation
-
Rust’s
format!
macro supports base-2({:b})
formatting. -
Simple and concise.
Method 5: Custom Function with Manual Stack Simulation
// Program 5: Convert Decimal to Binary using Manual Stack Simulation
fn stack_simulation(mut num: u32) -> String {
let mut stack = vec![];
while num > 0 {
stack.push((num % 2).to_string());
num /= 2;
}
stack.reverse();
stack.join("").or("0".to_string())
}
fn main() {
println!("Binary (11): {}", stack_simulation(11));
}
Output
Binary (11): 1011
Explanation
-
Simulates stack push and reverse behavior.
-
Returns
"0"
for zero input.
Method 6: Using Collect and Iterators
// Program 6: Convert Decimal to Binary using Functional Style
fn iterator_method(mut num: u32) -> String {
if num == 0 {
return "0".to_string();
}
let mut bits = vec![];
while num > 0 {
bits.push((num % 2).to_string());
num /= 2;
}
bits.iter().rev().cloned().collect()
}
fn main() {
println!("Binary (9): {}", iterator_method(9));
}
Output
Binary (9): 1001
Explanation
-
Uses functional approach with
.iter().rev().cloned().collect()
. -
Provides clean and idiomatic Rust code.
Conclusion
We explored six different Rust programs to perform decimal to binary conversion using recursion, bitwise operations, loop-based methods, and built-in formatting. Rust’s expressive syntax and memory safety guarantees make these implementations efficient and reliable.