How to convert any digital storage unit into all others (B, KB, MB, GB, TB, PB, EB, ZB, YB) in Swift

1 Answer

0 votes
import Foundation

/*
    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
func toBytes(_ value: Double, exponent: Int) -> Double {
    // 1024^exponent gives the multiplier for the unit
    value * pow(1024.0, Double(exponent))
}

// Convert bytes to any unit using its exponent
func fromBytes(_ bytes: Double, exponent: Int) -> Double {
    bytes / pow(1024.0, Double(exponent))
}

// Print all conversions from a given byte value
func printAll(_ bytes: Double) {
    let names = [
        "Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
    ]

    for (exp, name) in names.enumerated() {
        let converted = fromBytes(bytes, exponent: exp)
        print(String(format: "%8@: %.6f", name, converted))
    }

}

print("Digital Storage Unit Converter\n")

print("Enter value: ", terminator: "")
guard let valueInput = readLine(),
      let value = Double(valueInput.trimmingCharacters(in: .whitespaces)) else {
    print("Invalid value.")
    exit(1)
}

print("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ", terminator: "")
guard let unit = readLine()?.trimmingCharacters(in: .whitespaces) else {
    print("Invalid unit.")
    exit(1)
}

// Map unit string to exponent
let exponent: Int = {
    switch unit {
    case "B":  return 0
    case "KB": return 1
    case "MB": return 2
    case "GB": return 3
    case "TB": return 4
    case "PB": return 5
    case "EB": return 6
    case "ZB": return 7
    case "YB": return 8
    default:
        print("Unknown unit.")
        exit(1)
    }
}()

// Convert input to bytes
let bytes = toBytes(value, exponent: exponent)

// Print all conversions
print("\nConverted values:")
printAll(bytes)



/*
run:

Digital Storage Unit Converter

Enter value: 8
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): TB

Converted values:
Bytes: 8796093022208.000000
KB: 8589934592.000000
MB: 8388608.000000
GB: 8192.000000
TB: 8.000000
PB: 0.007812
EB: 0.000008
ZB: 0.000000
YB: 0.000000

*/

 



answered Aug 28 by avibootz

Related questions

...