将GB转换为字节


Convert Gigabytes to Bytes

我正试图从提交表单中将GB转换为字节。我四处搜索,找不到合适的内容。目前,当将字节转换为千兆字节时,我使用这种方法,效果非常好。

public function byteFormat($bytes, $unit = "", $decimals = 2) 
{
    $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4,
    'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
    $value = 0;
    if ($bytes > 0) {
    // Generate automatic prefix by bytes
    // If wrong prefix given
    if (!array_key_exists($unit, $units)) {
    $pow = floor(log($bytes)/log(1024));
    $unit = array_search($pow, $units);
    }
    // Calculate byte value by prefix
    $value = ($bytes/pow(1024,floor($units[$unit])));
    }
    // If decimals is not numeric or decimals is less than 0
    // then set default value
    if (!is_numeric($decimals) || $decimals < 0) {
    $decimals = 2;
    }
    // Format output
    return sprintf('%.' . $decimals . 'f '.$unit, $value);
}

似乎有很多字节转换为其他格式的例子,但没有相反的例子。

我已经看到我可以像一样转换数字1.5

round(($number[0] * 1073741824));

结果是12992276070,然而,当使用上面显示的字节格式方法时,我得到了下面的1610612736,这似乎是两种方法之间的很大区别。有人能提出一种更稳定的方法来将千兆字节转换为字节吗。

有两种不同的单位符号,十进制和二进制。正如你在这里看到的,十进制乘1000,二进制乘1024。因此,如果您使用"B"(字节),只需执行以下操作:

$bytenumber=$giga*pow(1024,3);

如果使用"b"(位):

$bitnumber=$giga*pow(1000,3);

p.S.:$giga是你的giga数字。

您只能在小数点后有数字的情况下获得准确的转换。如果你从1.29634吉开始,你会得到更接近它实际字节值的表示,而不是称它为1.3吉。这就是你想要的吗?

numberOfBytes = round (numberOfGb * 1073741824)

是你问题的确切答案。看来,你算错了。试着在计算器上检查一下。

另一个问题是,如果你的源号码是2位数,那么用多于或少于2位数给出答案是不正确的。正确的计数是:

source: 1.5GB
counting: 1.5GB*1073741824 B/GB= 1610612736 B
rounding to the last significant digit: 1610612736 B ~= 1.6e9 B
answer: 1.6e9 B

但是,当然,许多客户并不是真的想要正确的答案,他们想要自己的答案。这取决于你的选择。