Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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

1 Answer

0 votes
=begin
    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
=end

# Convert any unit to bytes using its exponent
def to_bytes(value, exponent)
    # 1024^exponent gives the multiplier for the unit
    value * (1024 ** exponent)
end

# Convert bytes to any unit using its exponent
def from_bytes(bytes, exponent)
    bytes / (1024 ** exponent)
end

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

    names.each_with_index do |name, exp|
        puts "#{name.rjust(8)}: #{format('%.6f', from_bytes(bytes, exp))}"
    end
end

puts "Digital Storage Unit Converter\n\n"

print "Enter value: "
value = gets.to_f

print "Enter unit (B, KB, MB, GB, TB, PB, EB, ZB, YB): "
unit = gets.strip

# Map unit string to exponent
exponent = case unit
    when "B"  then 0
    when "KB" then 1
    when "MB" then 2
    when "GB" then 3
    when "TB" then 4
    when "PB" then 5
    when "EB" then 6
    when "ZB" then 7
    when "YB" then 8
    else
        puts "Unknown unit."
        exit 1
end

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

# Print all conversions
puts "\nConverted values:"
print_all(bytes)


=begin
run:

Digital Storage Unit Converter

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

Converted values:
   Bytes: 6597069766656.000000
      KB: 6442450944.000000
      MB: 6291456.000000
      GB: 6144.000000
      TB: 6.000000
      PB: 0.005859
      EB: 0.000006
      ZB: 0.000000
      YB: 0.000000

=end

 



answered Aug 28 by avibootz

Related questions

...