【问题标题】:from bytes to new type conversion从字节到新类型的转换
【发布时间】:2017-05-30 03:27:43
【问题描述】:

我的值有点偏,有人可以看看我是如何转换它的,看看是否有什么问题我输入 64MB 为字节,然后使用 FileSizeConvert 将字节转换为 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

【问题讨论】:

  • 记住 2 的幂。2^10 = 1024。1 MB 是 1024 kb
  • 你是说方程式是正确的
  • 我是说输出是正确的。你说输出应该是 64000 但这是不正确的

标签: php type-conversion byte


【解决方案1】:

65536/1024=64。您需要记住以 2 的幂而不是以 10 为底的幂

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多