PHP convert KB MB GB TB etc to Bytes

后端 未结 8 2468
长发绾君心
长发绾君心 2020-12-16 18:53


I\'m asking how to convert KB MB GB TB & co. into bytes.
For example:

byteconvert(\"10KB\") // => 10240
byteconvert(\"10.5KB\") // =>          


        
相关标签:
8条回答
  • 2020-12-16 19:43

    One more solution (IEC):

    <?php
    
    class Filesize
    {
        const UNIT_PREFIXES_POWERS = [
            'B' => 0,
            ''  => 0,
            'K' => 1,
            'k' => 1,
            'M' => 2,
            'G' => 3,
            'T' => 4,
            'P' => 5,
            'E' => 6,
            'Z' => 7,
            'Y' => 8,
        ];
    
        public static function humanize($size, int $precision = 2, bool $useBinaryPrefix = false)
        {
            $base = $useBinaryPrefix ? 1024 : 1000;
            $limit = array_values(self::UNIT_PREFIXES_POWERS)[count(self::UNIT_PREFIXES_POWERS) - 1];
            $power = ($_ = floor(log($size, $base))) > $limit ? $limit : $_;
            $prefix = array_flip(self::UNIT_PREFIXES_POWERS)[$power];
            $multiple = ($useBinaryPrefix ? strtoupper($prefix) . 'iB' : $prefix . 'B');
            return round($size / pow($base, $power), $precision) . $multiple;
        }
    
        // ...
    }
    

    Source:

    https://github.com/mingalevme/utils/blob/master/src/Filesize.php https://github.com/mingalevme/utils/blob/master/tests/FilesizeTest.php

    0 讨论(0)
  • 2020-12-16 19:44
    function toByteSize($p_sFormatted) {
        $aUnits = array('B'=>0, 'KB'=>1, 'MB'=>2, 'GB'=>3, 'TB'=>4, 'PB'=>5, 'EB'=>6, 'ZB'=>7, 'YB'=>8);
        $sUnit = strtoupper(trim(substr($p_sFormatted, -2)));
        if (intval($sUnit) !== 0) {
            $sUnit = 'B';
        }
        if (!in_array($sUnit, array_keys($aUnits))) {
            return false;
        }
        $iUnits = trim(substr($p_sFormatted, 0, strlen($p_sFormatted) - 2));
        if (!intval($iUnits) == $iUnits) {
            return false;
        }
        return $iUnits * pow(1024, $aUnits[$sUnit]);
    }
    
    0 讨论(0)
提交回复
热议问题