use std::io;
/*
Digital storage conversion table:
Each unit is a power of 1024 relative to bytes.
Bytes (B) = 1024^0
Kilobytes (KB) = 1024^1
Megabytes (MB) = 1024^2
Gigabytes (GB) = 1024^3
Terabytes (TB) = 1024^4
Petabytes (PB) = 1024^5
Exabytes (EB) = 1024^6
Zettabytes (ZB)= 1024^7
Yottabytes (YB)= 1024^8
*/
// Convert any unit to bytes using its exponent
fn to_bytes(value: f64, exponent: i32) -> f64 {
// 1024^exponent gives the multiplier for the unit
value * 1024f64.powf(exponent as f64)
}
// Convert bytes to any unit using its exponent
fn from_bytes(bytes: f64, exponent: i32) -> f64 {
bytes / 1024f64.powf(exponent as f64)
}
// Print all conversions from a given byte value
fn print_all(bytes: f64) {
let names = [
"Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB",
];
for (exp, name) in names.iter().enumerate() {
println!("{:>8}: {:.6}", name, from_bytes(bytes, exp as i32));
}
}
fn main() {
println!("Digital Storage Unit Converter\n");
// Read value on the same line
print!("Enter value: ");
let _ = io::Write::flush(&mut std::io::stdout());
let mut value_input = String::new();
io::stdin().read_line(&mut value_input).unwrap();
let value: f64 = value_input.trim().parse().unwrap();
// Read unit on the same line
print!("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ");
let _ = io::Write::flush(&mut std::io::stdout());
let mut unit_input = String::new();
io::stdin().read_line(&mut unit_input).unwrap();
let unit = unit_input.trim();
// Map unit string to exponent
let exponent: i32 = match unit {
"B" => 0,
"KB" => 1,
"MB" => 2,
"GB" => 3,
"TB" => 4,
"PB" => 5,
"EB" => 6,
"ZB" => 7,
"YB" => 8,
_ => {
println!("Unknown unit.");
return;
}
};
// Convert input to bytes
let bytes = to_bytes(value, exponent);
// Print all conversions
println!("\nConverted values:");
print_all(bytes);
}
/*
run:
Digital Storage Unit Converter
Enter value: 368
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): PB
Converted values:
Bytes: 414331165718085632.000000
KB: 404620279021568.000000
MB: 395136991232.000000
GB: 385875968.000000
TB: 376832.000000
PB: 368.000000
EB: 0.359375
ZB: 0.000351
YB: 0.000000
*/