Skip to content

Instantly share code, notes, and snippets.

@rietta
Created August 12, 2014 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rietta/0e8454ade01a6408a5ca to your computer and use it in GitHub Desktop.
Save rietta/0e8454ade01a6408a5ca to your computer and use it in GitHub Desktop.
Quick and dirty command line tool to covert bytes to nibbles, kilobytes, megabytes, gigabytes, and terabytes.
#!/usr/bin/env ruby
##
# bytes
# Quick and dirty way to get a slate of byte conversions from the command line.
# Put it in your path and make it executable, by 'chmod 755 bytes'.
#
# Author: Frank Rietta
##
# Format a number with commas and a decimal without loading a heavy framework like Rails.
# Thanks to tokland's answer at https://codereview.stackexchange.com/questions/28054/separate-numbers-with-commas-in-ruby
def separate_comma(number)
whole, decimal = number.to_s.split(".")
whole_with_commas = whole.chars.to_a.reverse.each_slice(3).map(&:join).join(",").reverse
[whole_with_commas, decimal].compact.join(".")
end
# Prepare an answer for output
def answer(value, unit_name)
puts "#{unit_name} : #{separate_comma(value)}"
end
# The fundamental byte constant
K = 1024.0
# Get the number off the command line argument list to convert, treat it as an integer
bytes = ARGV.last.to_i
# Conversions
nibbles = bytes * 2
kb = bytes.to_f / K
mb = kb / K
gb = mb / K
tb = gb / K
# Output answers
answer nibbles, 'nibbles '
answer bytes, 'bytes '
answer kb.round(4), 'kilobytes'
answer mb.round(4), 'megabytes'
answer gb.round(4), 'gigabytes'
answer tb.round(4), 'terabytes'
# That's it
@rietta
Copy link
Author

rietta commented Aug 12, 2014

Example usage bytes 994050048
Outputs

nibbles   : 1,988,100,096
bytes     : 994,050,048
kilobytes : 970,752.0
megabytes : 948.0
gigabytes : 0.9258
terabytes : 0.0009

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment