Skip to content

Instantly share code, notes, and snippets.

@palemoky
Created August 27, 2016 01:13
Show Gist options
  • Save palemoky/39127ff4248fbc5271a661a671660a99 to your computer and use it in GitHub Desktop.
Save palemoky/39127ff4248fbc5271a661a671660a99 to your computer and use it in GitHub Desktop.
实现文件单位的快速转换,这是我的第一个函数
<?php
/**
* Created by PhpStorm
* User: Xinyu
* Date: 16/8/25
* Time: 下午10:09
*/
function unitConvert($scale){
if($scale >= (1<<30)){
$scale /= (1<<30);
$scale = round($scale,2);
echo $scale,'GB';
}else if($scale >= (1<<20)){
$scale /= (1<<20);
$scale = round($scale,2);
echo $scale,'MB';
}else if($scale >= (1<<10)){
$scale /= (1<<10);
$scale = round($scale,2);
echo $scale,'KB';
}else{
echo $scale,'B';
}
}
?>
@palemoky
Copy link
Author

function byteConvert($size) {
    switch ($size) {
        case $size >= 1 << 50:
            $unit = 1 << 50;
            $unit_name = 'PB';
            break;
        case $size >= 1 << 40:
            $unit = 1 << 40;
            $unit_name = 'TB';
            break;
        case $size >= 1 << 30:
            $unit = 1 << 30;
            $unit_name = 'GB';
            break;
        case $size >= 1 << 20:
            $unit = 1 << 20;
            $unit_name = 'MB';
            break;
        case $size >= 1 << 10:
            $unit = 1 << 10;
            $unit_name = 'KB';
            break;
        default:
            $unit = $size;
            $unit_name = 'B';
    }

    $size /= $unit;

    return round($size, 2) . $unit_name;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment