Skip to content

Instantly share code, notes, and snippets.

@seungwon0
Last active January 27, 2016 07:51
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 seungwon0/8b9a0a21897a45a86501 to your computer and use it in GitHub Desktop.
Save seungwon0/8b9a0a21897a45a86501 to your computer and use it in GitHub Desktop.
prints the input number as byte, KiB, MiB and GiB unit
#!/usr/bin/env perl
#
# bytes - prints the input number as byte, KiB, MiB and GiB unit
#
# Prints the input number as byte, KiB, MiB and GiB unit.
#
# Seungwon Jeong <seungwon0@gmail.com>
#
# Copyright (C) 2016 by Seungwon Jeong
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
use perl5i::2;
use Readonly;
if ( @ARGV != 1 ) {
print <<"END_USAGE";
Usage: $PROGRAM_NAME <number>
Example usage:
$PROGRAM_NAME 1048576
$PROGRAM_NAME 0x100000
END_USAGE
exit 2;
}
my $number = $ARGV[0];
if ( $number =~ /^0/ ) {
$number = oct $number;
}
Readonly my $KIBI => 1024;
my $bytes = $number;
my $kibibytes = $bytes / $KIBI;
my $mibibytes = $kibibytes / $KIBI;
my $gibibytes = $mibibytes / $KIBI;
printf "%d bytes\n", $bytes;
printf "%.2f KiB\n", $kibibytes;
printf "%.2f MiB\n", $mibibytes;
printf "%.2f GiB\n", $gibibytes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment