Abro, März 2009

Human Readable Bytes – Sorry to raghuveer & Co.

php(sorry folks i’m too lazy for an english version right now. the source’s what matters.)

Jap ich bin total am ausmisten, ich will die nächsten Tage erstmal nichts mehr mit PHP zu tun haben. Ich hab nämlich jetzt Urlaub *fg* Deswegen hier nochmal ein dickes Sorry an die PHP.net Community. Ihr werdet mir nochmal zum verhängnis ;O) Problem ist ja immer dass man einmal geposteten Source nicht korregieren kann. Und wenn man’s dann doch macht ist das fast schon Spam. Total doof, wenn das dann in ernsthaften Projekten aufgegriffen und weiterverarbeitet wird. Im vorliegenden Fall geht’s einfach darum einen beliebigen Bytewert so zu formatieren, dass ihn auch normale Menschen lesen können. Der Code erklärt sich ja selbst. Unglaublich basic. Ich hatte das schon ewig vor, also hier für die eingeweihten die byte conversion ohne Macken :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
  /**
  * converts a bytevalue into the highest possible unit
  * and adds it's sign.
  * @version  2009-01-27 03:50h
  *
  * @param    bigint|float  $bytes    -bytevalue to convert
  * @param    int           $exp_max  -maximal allowed exponent (0='B', 1='KiB', 2='MiB', ...)
  *
  * @return   string
  */
  function byte_convert($bytes, $exp_max=null)
  {
    $symbol = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
 
    $exp = 0;
    if( $exp_max === null )
      $exp_max = count($symbol)-1;
    $converted_value = 0;
 
    if( $bytes > 0 )
    {
      $exp = floor( log($bytes)/log(1024) );
      if( $exp > $exp_max )
        $exp = $exp_max;
      $converted_value = ( $bytes/pow(1024,$exp) );
    }
 
    return number_format($converted_value,2,',','.').' '.$symbol[$exp];
  }
?>

…Oder zumindest ohne Macken wenn man von der Formatierung hier im Blog absieht. Dieses Spitze-Klammer-Double-Encoding ist echt furchtbar -.-

  • Twitter
  • Facebook
  • Google Bookmarks
  • MisterWong.DE

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

*