dourao3960 2017-01-15 01:39
浏览 52

从字节到新类型转换

My value is slightly off could someone have a look at how I'm converting it see if there is anything wrong I'm inputting 64MB to bytes and then converting bytes to KB with FileSizeConvert and I'm not quite sure if it's right could someone please have a look and see if there needs to be any changes for 64mb there should be 64000KB and my ouput is 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;     
}

usage:

$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条回答 默认 最新

  • dongliulu1122 2017-01-15 01:44
    关注

    65536/1024=64. You need to remember to think in powers of 2 not base 10

    评论

报告相同问题?

悬赏问题

  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码