Convert bytes to readable units in Perl

February 6th, 2013
232 words · 1 minutes read

I recently used code similar to that below in VPSMon, and came across a need where it would be convenient to display bytes as a more human-friendly string in Perl. Basically I’m building a script, and I want to convert the amount of available/free RAM on a machine from bytes to gigabytes for display to a user, but I figured may as well cover all bases and have this around in case it needs to display other units/multiples in the future.

So, with a little bit of tweaking, here it is!

Pass bytes as the first argument, and optionally a ‘truesy’ second argument if you’d rather the multiplier of 1000 vs the default 1024.

1
2
3
4
5
6
7
8
9
10
sub bytes_to_human {
my ($bytes, $mul) = @_;
return $bytes . " B" if ($bytes < 1024);
$mul = $mul ? 1000 : 1024;

my $exp = int(log($bytes) / log($mul));
my @pre = qw/ K M G T P E /;
my $pre = $pre[$exp-1] . ( $mul == 1024 ? 'i' : '' );
return sprintf("%.2f %sB", ($bytes / POSIX::pow($mul, $exp)), $pre);
}

Edit Turns out I found that Java code from VPSMon :)

1
2
3
4
5
6
public String bytes2human(long bytes) {
if (bytes < 1024) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(1024));
char pre = "KMGTPE".charAt(exp-1);
return String.format("%.2f %sB", bytes / Math.pow(1024, exp), pre);
}


Posted in: Tech
Tagged: code, perl
Originally published at: http://texh.net/blog/convert-bytes-to-readable-units-in-perl