Reply to Re: Needed Optimization for byteconversion function

Your name:

Reply:


Posted by Kimmo Laine on 12/20/05 15:37

"Prince of Code" <princeofcode@gmail.com> wrote in message
news:1135084052.220659.211190@g49g2000cwa.googlegroups.com...
> Hey all,
> I am writing a function that converts given bytes into KB , MB
> or GB. This function will work as in Windows if the file size is too
> large in MB it will show as 2.34 MB instead 23400 KB( for example )
>
> I find still it can be optimized. Ideas welcome
>
> /*
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Function : byteConversion( $byte )
> Description : This functions converts given bytes into human
> readable format.
> Params : raw bytes
> return : byte in Readable format 5.23 MB 220 KB
> Version : 1.0
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> */
>
> function byteConversion( $byte ){
>
> $result = 0;
>
> // becoz 1 KB = 1024 Bytes
> if( $byte <= 1023 ){
> $result = round($byte,2)."Byte(s)";
> // becoz 1 MB = 1024 KB = 1024 * 1024
> }elseif( $byte <= 1048575 ){
> $byte = $byte / 1024 ;
> $result = round($byte,2)." KB ";
> // becoz 1 GB = 1024 MB = 1024 * 1024 * 1024
> }elseif( $byte <= 1073741823 ){
> $byte = $byte / 1048576 ;
> $result = round($byte,2)." MB ";
> // becoz 1 TB = 1024 GB = 1024 * 1024 * 1024 * 1024
> }elseif( $byte <= 1099511627775 ){
> $byte = $byte / 1073741824 ;
> $result = round($byte,2)." GB ";
> }
>
> return $result;
> }

clearly it can be done with a loop structure:

function byteConversion($bytes){
$sizes = array('byte(s)', 'KB', 'MB', 'GB', 'TB');
for($multiples=0, $result=$bytes; $result>=1024; $multiples++,
$result/=1024);
return number_format($result,2).' '.$sizes[$multiples];
}

//examples of usage:
echo byteConversion(8192);
echo '<br/>';
echo byteConversion(1024);
echo '<br/>';
echo byteConversion(filesize(__FILE__));
echo '<br/>';
echo byteConversion(4700000000);
echo '<br/>';
echo byteConversion(1440000);


--
"En ole paha ihminen, mutta omenat ovat elinkeinoni." -Perttu Sirviφ
antaatulla.sikanautaa@gmail.com.NOSPAM.invalid

[Back to original message]


УдалСнная Ρ€Π°Π±ΠΎΡ‚Π° для программистов  •  Как Π·Π°Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ Π½Π° Google AdSense  •  England, UK  •  ΡΡ‚Π°Ρ‚ΡŒΠΈ Π½Π° английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Π‘Π°ΠΉΡ‚ ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ Π² Π‘Ρ‚ΡƒΠ΄ΠΈΠΈ Π’Π°Π»Π΅Π½Ρ‚ΠΈΠ½Π° ΠŸΠ΅Ρ‚Ρ€ΡƒΡ‡Π΅ΠΊΠ°
ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ΠΈΠ΅ ΠΈ ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΊΠ° Π²Π΅Π±-сайтов, Ρ€Π°Π·Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΠ½ΠΎΠ³ΠΎ обСспСчСния, поисковая оптимизация