/*
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
function toBytes(value: number, exponent: number): number {
// 1024^exponent gives the multiplier for the unit
return value * Math.pow(1024, exponent);
}
// Convert bytes to any unit using its exponent
function fromBytes(bytes: number, exponent: number): number {
return bytes / Math.pow(1024, exponent);
}
// Print all conversions from a given byte value
function printAll(bytes: number): void {
const names: string[] = [
"Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
];
names.forEach((name: string, exp: number) => {
console.log(`${name.padStart(8)}: ${fromBytes(bytes, exp).toFixed(6)}`);
});
}
console.log("Digital Storage Unit Converter\n");
// Node.js input handling
import readline from "readline";
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter value: ", (valueInput: string) => {
const value: number = parseFloat(valueInput);
rl.question("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ", (unit: string) => {
// Map unit string to exponent
let exponent: number = -1;
if (unit === "B") exponent = 0;
if (unit === "KB") exponent = 1;
if (unit === "MB") exponent = 2;
if (unit === "GB") exponent = 3;
if (unit === "TB") exponent = 4;
if (unit === "PB") exponent = 5;
if (unit === "EB") exponent = 6;
if (unit === "ZB") exponent = 7;
if (unit === "YB") exponent = 8;
if (exponent < 0) {
console.log("Unknown unit.");
rl.close();
return;
}
// Convert input to bytes
const bytes: number = toBytes(value, exponent);
// Print all conversions
console.log("\nConverted values:");
printAll(bytes);
rl.close();
});
});
/*
run:
Digital Storage Unit Converter
Enter value: 380
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): PB
Converted values:
Bytes: 427841964600197120.000000
KB: 417814418554880.000000
MB: 408021893120.000000
GB: 398458880.000000
TB: 389120.000000
PB: 380.000000
EB: 0.371094
ZB: 0.000362
YB: 0.000000
*/