將位元組數轉換成使用者可讀的格式_2

來源:互聯網
上載者:User
=Start=

接上篇「 將位元組數轉換成使用者可讀的格式」,上篇文章主要是使用Linux下已有的工具(numfmt,需要 GNU coreutils >= 8.21)進行轉換,但是我記錄這篇文章的最初目的是自己編碼實現相關功能(比如寫成一個alias/function放在.bashrc中方便日常使用),這篇文章的內容就是介紹通過各種程式設計語言來實現該功能。

參考解答:

1.awk/gawk

# OKecho "12454162221" | awk '    BEGIN {       split("B,KB,MB,GB,TB", Units, ",");    }    {       u = 1;       while ($1 >= 1024) {          $1 = $1 / 1024;          u += 1       }       $1 = sprintf("%.2f %s", $1, Units[u]);       print $0;    }' # OKecho "12454162221" | gawk 'BEGIN { split("KMGTPEZY",suff,//)}{  match($0,/([0-9]+)/,bits)  sz=bits[1]+0  i=0; while ((sz>1024)&&(i    

2.Perl

echo "12454162221" | perl -ne 'if (/^(\d+)/){$l=log($1+.1);$m=int($l/log(1024)); printf("%6.1f\t%s\n",($1/(2**(10*$m))),("K","M","G","T","P")[$m-1]);}' # 最大以G為單位echo "12454162221" | perl -pe 's{([0-9]+)}{sprintf "%.1f%s", $1>=2**30? ($1/2**30, "G"): $1>=2**20? ($1/2**20, "M"): $1>=2**10? ($1/2**10, "K"): ($1, "")}e'

3.Python

defbytes_format(filesize, unit=1024):    unit = float(unit)    for countin ['Bytes','KB','MB','GB', 'TB', 'PB']:        if 0 < filesize < unit:            return '{0:.3f} {1}'.format(filesize, count)        filesize /= unit printbytes_format(12454162221)

4.PHP

 $bytesize){      $numbers /= $bytesize;      $index++;  }  return("".round($numbers, 2)." ".$readable[$index]);}echobytes_format(12454162221) . "\n";echobytes_format(124541622210) . "\n";echobytes_format(1245416222100) . "\n";

參考連結:

  • http://unix.stackexchange.com/questions/44040/a-standard-tool-to-convert-a-byte-count-into-human-kib-mib-etc-like-du-ls1
  • http://stackoverflow.com/questions/15854332/file-size-in-human-readable-format
  • http://www.kossboss.com/linux—bytes-to-human-readable-command
  • http://ram.kossboss.com/humanbytesawk/
  • http://ram.kossboss.com/linux-bytes-to-human-readable-command/
  • http://superuser.com/questions/553976/how-to-display-the-size-in-human-readable-format-in-the-find-command/554027#554027
  • http://serverfault.com/questions/62411/how-can-i-sort-du-h-output-by-size
  • http://codesnippets.fesslersoft.de/format-bytes-to-human-readable-size/
  • http://www.developerfeed.com/how-convert-bytes-human-readable-string-format-php/
  • http://www.ivankristianto.com/tips-convert-your-numbers-to-human-readable-format/

=END=

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.