package main
import (
"bufio"
"fmt"
"math"
"os"
"strings"
)
/*
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 float64, exponent int) float64 {
// 1024^exponent gives the multiplier for the unit
return value * math.Pow(1024.0, float64(exponent))
}
// Convert bytes to any unit using its exponent
func fromBytes(bytes float64, exponent int) float64 {
return bytes / math.Pow(1024.0, float64(exponent))
}
// Print all conversions from a given byte value
func printAll(bytes float64) {
names := []string{
"Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB",
}
for exp, name := range names {
fmt.Printf("%8s: %.6f\n", name, fromBytes(bytes, exp))
}
}
func main() {
fmt.Println("Digital Storage Unit Converter\n")
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter value: ")
var value float64
fmt.Scanf("%f", &value)
fmt.Print("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ")
unitInput, _ := reader.ReadString('\n')
unit := strings.TrimSpace(unitInput)
// Map unit string to exponent
exponent := -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 {
fmt.Println("Unknown unit.")
return
}
// Convert input to bytes
bytes := toBytes(value, exponent)
// Print all conversions
fmt.Println("\nConverted values:")
printAll(bytes)
}
/*
run:
Digital Storage Unit Converter
Enter value: 338
Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): PB
Converted values:
Bytes: 380554168512806912.000000
KB: 371634930188288.000000
MB: 362924736512.000000
GB: 354418688.000000
TB: 346112.000000
PB: 338.000000
EB: 0.330078
ZB: 0.000322
YB: 0.000000
*/