从字节到新类型转换

时间:2017-01-15 01:39:31

标签: php type-conversion byte

我的价值略有下降,如果有人看看我如何转换它,看看是否有什么问题我输入64MB到字节,然后用FileSizeConvert和I'将字节转换为KB。我不太确定是否有人可以请一看,看看是否需要对64mb进行任何更改,应该有64000KB,我的输出是65536KB。

public static function convertToBytes($from){
    $number = substr($from, 0, -2);

    switch(strtoupper(substr($from,-2))){
        case "KB":
            return $number*1024;
        case "MB":
            return $number*pow(1024,2);
        case "GB":
            return $number*pow(1024,3);
        case "TB":
            return $number*pow(1024,4);
        case "PB":
            return $number*pow(1024,5);
        default:
            return $from;
    }
}

public static function FileSizeConvert($bytes, $type)
{

    $types = ['TB', 'GB', 'MB', 'KB', 'B'];     
    $index = array_search($type, array_values($types));

    $bytes = floatval($bytes);
        $arBytes = array(
            0 => array(
                "UNIT" => "TB",
                "VALUE" => pow(1024, 4)
            ),
            1 => array(
                "UNIT" => "GB",
                "VALUE" => pow(1024, 3)
            ),
            2 => array(
                "UNIT" => "MB",
                "VALUE" => pow(1024, 2)
            ),
            3 => array(
                "UNIT" => "KB",
                "VALUE" => 1024
            ),
            4 => array(
                "UNIT" => "B",
                "VALUE" => 1
            ),
        );

    $result = $bytes / $arBytes[$index]["VALUE"];
    $result = str_replace(".", "," , strval(round($result, 2)))." ".$arBytes[$index]["UNIT"];
    return $result;     
}

用法:

$max_file_size = Helper::convertToBytes(ini_get('upload_max_filesize') . 'B'); // value is 64MB
$kb = Helper::FileSizeConvert($max_file_size, 'KB'); // ouput 65536 KB

1 个答案:

答案 0 :(得分:0)

一千○二十四分之六万五千五百三十六= 64。你需要记住以2的幂而不是基数10来思考