Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active October 5, 2015 21:37
Show Gist options
  • Save craiga/2880386 to your computer and use it in GitHub Desktop.
Save craiga/2880386 to your computer and use it in GitHub Desktop.
Format a number of bytes.
<?php
/**
* Format a number of bytes.
*
* Format a number of bytes into a readable string in either IETF (kibibyte,
* 1024 bytes) or SI (kilobyte, 1000 bytes) units.
* Produces output like "1 byte", "28 bytes", "4 MB" or "22 GiB".
*
* @param $memory The number of bytes to format. The result of
* {@link http://php.net/memory_get_usage memory_get_usage}
* is used if omitted.
* @param $precision The number of decimal places to display. 0 if omitted.
* @param $useSiUnits Whether to use SI units or not. IETF units by default.
*
* @author Craig Anderson <craiga@craiga.id.au>
* @link http://gist.github.com/2880386
*/
function format_memory($memory = null, $precision = 0, $useSiUnits = false)
{
if(is_null($memory))
{
$memory = memory_get_usage();
}
$result = null;
if($memory == 1)
{
$result = "1 byte";
}
else
{
$unit = "bytes";
if($useSiUnits) {
if(abs($memory) > 1999)
{
$memory = $memory / 1000;
$unit = "KB";
}
if(abs($memory) > 1999)
{
$memory = $memory / 1000;
$unit = "MB";
}
if(abs($memory) > 1999)
{
$memory = $memory / 1000;
$unit = "GB";
}
}
else {
if(abs($memory) > 2047)
{
$memory = $memory / 1024;
$unit = "KiB";
}
if(abs($memory) > 2047)
{
$memory = $memory / 1024;
$unit = "MiB";
}
if(abs($memory) > 2047)
{
$memory = $memory / 1024;
$unit = "GiB";
}
}
$result = sprintf("%s %s", number_format($memory, $precision), $unit);
}
return $result;
}
<?php
require_once("format_memory.php");
$numByteses = array(-1, 0, 1, 999, 1000, 1001, 1023, 1024, 1025, 2047, 2048, 2049, 3000000, 3000001, 3145727, 3145728, 3145729);
printf("Num Bytes SI Non-SI\n");
foreach($numByteses as $key => $numBytes) {
printf("%-10s %-20s %s\n", number_format($numBytes), format_memory($numBytes, 3, true), format_memory($numBytes, 3, false));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment