Convert bytes to readable units in Perl/Java/PHP
February 6th, 2013
291 words · 2 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 | sub bytes_to_human { |
Edit Turns out I found that Java code from VPSMon :)1
2
3
4
5
6public 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 sometimes1
2
3
4
5
6
7
8
9
10function 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);
}