Convert bytes to readable units in Perl/Java/PHP

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.

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 :)

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);
}

Another Edit Turns out I still write PHP sometimes

function bytesToHuman ($bytes, $mul = 1024) {
  if ($bytes < $mul) {
      return $bytes . "B";
  }

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

Categories: Tech
Originally published at: http://texh.net/blog/convert-bytes-to-readable-units-in-perl
‹ Previous Post Next Post ›