Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format bytes to kilobytes, megabytes, gigabytes

Tags:

php

People also ask

How do you convert bytes to kilobytes to megabytes?

To convert smaller units to larger units (convert bytes to kilobytes or megabytes) you simply divide the original number by 1,024 for each unit size along the way to the final desired unit.

How many bytes are in a KB MB GB?

KB, MB, GB - A kilobyte (KB) is 1,024 bytes. A megabyte (MB) is 1,024 kilobytes. A gigabyte (GB) is 1,024 megabytes. A terabyte (TB) is 1,024 gigabytes.

How do you convert bytes to gigabytes?

In other words, if you want to convert a storage size from bytes to MB, you need to divide it with 102 * 1024. Similarly, to convert it to GB, you need to divide it by 1024 * 1024 * 1024.

Is 1024 KB is equal to 1GB?

1GB = 1024MB. 1MB = 1024KB. 1kB = 1024 Bytes. 1 Byte = 8 bits.


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

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

(Taken from php.net, there are many other examples there, but I like this one best :-)


This is Chris Jester-Young's implementation, cleanest I've ever seen, combined with php.net's and a precision argument.

function formatBytes($size, $precision = 2)
{
    $base = log($size, 1024);
    $suffixes = array('', 'K', 'M', 'G', 'T');   

    return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}

echo formatBytes(24962496);
// 23.81M

echo formatBytes(24962496, 0);
// 24M

echo formatBytes(24962496, 4);
// 23.8061M

Pseudocode:

$base = log($size) / log(1024);
$suffix = array("", "k", "M", "G", "T")[floor($base)];
return pow(1024, $base - floor($base)) . $suffix;

Just divide it by 1024 for kb, 1024^2 for mb and 1024^3 for GB. As simple as that.


This is Kohana's implementation, you could use it:

public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
{
    // Format string
    $format = ($format === NULL) ? '%01.2f %s' : (string) $format;

    // IEC prefixes (binary)
    if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
    {
        $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
        $mod   = 1024;
    }
    // SI prefixes (decimal)
    else
    {
        $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
        $mod   = 1000;
    }

    // Determine unit to use
    if (($power = array_search((string) $force_unit, $units)) === FALSE)
    {
        $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
    }

    return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
}