Skip to content

Instantly share code, notes, and snippets.

@borisguery
Created December 20, 2012 14:16
Show Gist options
  • Save borisguery/4345523 to your computer and use it in GitHub Desktop.
Save borisguery/4345523 to your computer and use it in GitHub Desktop.
format bytes to the best fitted unit
#!/usr/bin/env php
<?php
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return sprintf('%4.02f %s', round($bytes, $precision), $units[$pow]);
}
if (2 !== $argc) {
printf("Usage: %s [bytes]\n", $argv[0]);
exit(-1);
}
list(, $bytes) = $argv;
printf("%s => %s\n", $bytes, formatBytes($bytes));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment