Human-Readable Byte Formatter and Parser
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
Two complementary jobs that show up constantly: turning a raw byte count into something a human reads at a glance, and turning a config string like 256MB back into an integer for comparison. Doing both with one consistent base-1024 convention avoids the classic bug where one part of the code uses 1000 and another uses 1024 and your limits are quietly off by a few percent.
formatBytes picks the right unit by taking the base-1024 logarithm of the size, clamps it so absurd inputs do not overflow the unit table, then scales and rounds. parseBytes does the inverse with a single regex that captures the numeric part and an optional suffix, mapping the suffix to a power of 1024. Both are pure built-in PHP and round-trip cleanly for whole units.
function formatBytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$bytes = max($bytes, 0);
$pow = $bytes > 0 ? (int) floor(log($bytes, 1024)) : 0;
$pow = min($pow, count($units) - 1);
$value = $bytes / (1024 ** $pow);
return round($value, $precision) . ' ' . $units[$pow];
}
function parseBytes(string $size): int {
if (!preg_match('/^([\d.]+)\s*([KMGTP]?B)?$/i', trim($size), $m)) {
throw new InvalidArgumentException("Bad size: $size");
}
$map = ['B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5];
$unit = strtoupper($m[2] ?? 'B');
return (int) round((float) $m[1] * (1024 ** ($map[$unit] ?? 0)));
}
echo formatBytes(1536) . "\n"; // 1.5 KB
echo formatBytes(5368709120) . "\n"; // 5 GB
echo parseBytes('256 MB') . "\n"; // 268435456
echo parseBytes('1.5GB') . "\n"; // 1610612736
Comments
No comments yet
Be the first to share your thoughts!