-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter
28 lines (23 loc) · 941 Bytes
/
converter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::io;
fn main() {
println!("Enter a decimal number to convert to binary:");
// Get user input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read input");
let number: u32 = input.trim().parse().expect("Please enter a valid integer");
// Convert the number to binary representation
let mut binary_representation = String::new();
// Starting from 2^7 for an 8-bit result (for illustration purposes),
// but this can be adjusted for more bits if needed.
let mut remainder = number;
for i in (0..8).rev() {
let power_of_two = 1 << i; // equivalent to 2^i
if remainder >= power_of_two {
binary_representation.push('1');
remainder -= power_of_two;
} else {
binary_representation.push('0');
}
}
println!("The binary representation of {} is: {}", number, binary_representation);
}