Rumah >pembangunan bahagian belakang >tutorial php >将字节数转换成用户可读的格式_2
=Start=
接上篇「 将字节数转换成用户可读的格式」,上篇文章主要是使用Linux下已有的工具(numfmt,需要 GNU coreutils >= 8.21)进行转换,但是我记录这篇文章的最初目的是自己编码实现相关功能(比如写成一个alias/function放在.bashrc中方便日常使用),这篇文章的内容就是介绍通过各种编程语言来实现该功能。
# 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<length(suff))) { sz/=1024;i++ } if (i) printf("%.3f %siB\n",sz,suff[i]) else printf("%3i B\n",sz)}' # OKecho "12454162221" | awk '{ xin=$1; if(xin==0) { print "0 B"; } else { x=(xin<0?-xin:xin); s=(xin<0?-1:1); split("B KiB MiB GiB TiB PiB",type); for(i=5;y < 1;i--) { y=x/(2^(10*i)); } print y*s " " type[i+2]; };}'
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'
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)
<?php function bytes_format($numbers, $bytesize = 1024) { $readable = array("", "KB", "MB", "GB", "TB", "PB"); $index = 0; while($numbers > $bytesize){ $numbers /= $bytesize; $index++; } return("".round($numbers, 2)." ".$readable[$index]);}echobytes_format(12454162221) . "\n";echobytes_format(124541622210) . "\n";echobytes_format(1245416222100) . "\n";
=END=