php bytes conversion

PHP byte conversion function

Generelly we need to display the file size in file sharing applications. Here we use below function to display the size in bytes with filesize function.

function byte_convert($bytes)
  {
    $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
 
    $exp = 0;
    $converted_value = 0;
    if( $bytes > 0 )
    {
      $exp = floor( log($bytes)/log(1024) );
      $converted_value = ( $bytes/pow(1024,floor($exp)) );
    }
 
    return sprintf( '%.2f '.$symbol[$exp], $converted_value );
        //we can't use PHP integer unsigned as some systems use 32 bit and other 64 bit ,so here we use C style function sprintf
  }

 

File size stadards

computer data and file size is normally measured in binary code using the binary number system, the prefixes for the multiples are based on the metric system!  The nearest binary number to 1,000 is 2^10 or 1,024; thus 1,024 bytes was named a Kilobyte.

New IEC Standard
bit bit 0 or 1
byte B 8 bits
kibibit Kibit 1024 bits
kilobit kbit 1000 bits
kibibyte (binary) KiB 1024 bytes
kilobyte (decimal) kB 1000 bytes
megabit Mbit 1000 kilobits
mebibyte (binary) MiB 1024 kibibytes
megabyte (decimal) MB 1000 kilobytes
gigabit Gbit 1000 megabits
gibibyte (binary) GiB 1024 mebibytes
gigabyte (decimal) GB 1000 megabytes
terabit Tbit 1000 gigabits
tebibyte (binary) TiB 1024 gibibytes
terabyte (decimal) TB 1000 gigabytes
petabit Pbit 1000 terabits
pebibyte (binary) PiB 1024 tebibytes
petabyte (decimal) PB 1000 terabytes
exabit Ebit 1000 petabits
exbibyte (binary) EiB 1024 pebibytes
exabyte (decimal) EB 1000 petabytes

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">