Created
December 20, 2012 14:16
-
-
Save borisguery/4345523 to your computer and use it in GitHub Desktop.
format bytes to the best fitted unit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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