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

1 Answer

0 votes
import math

"""
    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
def to_bytes(value, exponent):
    # 1024^exponent gives the multiplier for the unit
    return value * math.pow(1024.0, exponent)

# Convert bytes to any unit using its exponent
def from_bytes(bytes_value, exponent):
    return bytes_value / math.pow(1024.0, exponent)

# Print all conversions from a given byte value
def print_all(bytes_value):
    names = [
        "Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
    ]

    for exp, name in enumerate(names):
        print(f"{name:8}: {from_bytes(bytes_value, exp):.6f}")

def main():
    print("Digital Storage Unit Converter\n")

    value = float(input("Enter value: "))
    unit = input("Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): ")

    # 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:
        print("Unknown unit.")
        return

    # Convert input to bytes
    bytes_value = to_bytes(value, exponent)

    # Print all conversions
    print("\nConverted values:")
    print_all(bytes_value)

if __name__ == "__main__":
    main()



"""
run:

Digital Storage Unit Converter

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

Converted values:
Bytes   : 388435467860705280.000000
KB      : 379331511582720.000000
MB      : 370440929280.000000
GB      : 361758720.000000
TB      : 353280.000000
PB      : 345.000000
EB      : 0.336914
ZB      : 0.000329
YB      : 0.000000

"""

 



answered Aug 28 by avibootz

Related questions

...