Created
August 12, 2014 01:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage
bytes 994050048
Outputs