Skip to main content

How to Convert Bytes to Kilobytes, Megabytes, Gigabytes in Batch Script

When working with file sizes or disk space, raw byte counts are difficult for humans to interpret. A value like 5368709120 is far less meaningful than 5 GB. Converting bytes into their appropriate human-readable unit (KB, MB, GB) requires a series of divisions by 1024. In Batch, this is straightforward for values under 2 GB, but requires a PowerShell bridge for larger numbers.

In this guide, we will demonstrate how to build a dynamic byte-to-unit converter.

The Strategy: The Unit Ladder

  1. Start with the raw byte count.
  2. If the value is 1024 or greater, divide by 1024 and advance to the next unit.
  3. Repeat until the value is under 1024 or you've reached the largest unit (TB).

Implementation Script

@echo off
setlocal enabledelayedexpansion

:: 1. Define the raw size in bytes
set "bytes=1572864"

:: 2. Define unit names
set "unit=Bytes"

echo Raw Input: !bytes! bytes

:: 3. Check each threshold and climb the unit ladder
set "val=!bytes!"

if !val! GEQ 1024 (
set /a "val/=1024"
set "unit=KB"
)
if !val! GEQ 1024 (
set /a "val/=1024"
set "unit=MB"
)
if !val! GEQ 1024 (
set /a "val/=1024"
set "unit=GB"
)
if !val! GEQ 1024 (
set /a "val/=1024"
set "unit=TB"
)

echo.
echo ==========================================
echo FORMATTED: !val! !unit!
echo ==========================================
pause
Sequential if Blocks Require Delayed Expansion

Each if !val! GEQ 1024 block modifies val and unit, and the next if block must see the updated value. This only works correctly with delayed expansion (!val!). Using percent expansion (%val%) would cause every block to evaluate the same original value from parse time, potentially skipping multiple units in a single pass or applying the wrong unit label.

Why Convert Byte Sizes?

  1. Disk Reports: Showing an administrator "You have 45 GB free" is far more useful than showing 48,318,382,080 bytes.
  2. Quota Alerts: Triggering an alert when a user exceeds "500 MB" requires converting their folder size from bytes.
  3. Log Summaries: When scanning directory sizes, presenting results in the most appropriate unit (KB for small files, GB for large ones) makes the report immediately actionable.

Important Limitations

32-Bit Ceiling

Batch's set /a is limited to signed 32-bit integers (max 2,147,483,647). This means the script cannot handle raw byte values larger than approximately 2 GB. For larger files, you must use the PowerShell bridge below.

No Decimal Precision

Batch performs integer division only. The conversion 1572864 / 1024 / 1024 gives 1 (integer), not 1.5. You lose the fractional component at each division step. After multiple divisions, the displayed value can be noticeably lower than the true value.

PowerShell Bridge (For Large Files and Decimal Precision)

@echo off
setlocal

:: Example: Convert a large file size to human-readable format
set "filepath=C:\path\to\large_file.iso"

if not exist "%filepath%" (
echo [ERROR] File not found: %filepath%
pause
exit /b
)

for %%F in ("%filepath%") do set "size=%%~zF"

for /f "usebackq delims=" %%R in (`
powershell -NoProfile -Command ^
"$s = [int64]%size%; if ($s -ge 1TB) { '{0:N2} TB' -f ($s/1TB) } elseif ($s -ge 1GB) { '{0:N2} GB' -f ($s/1GB) } elseif ($s -ge 1MB) { '{0:N2} MB' -f ($s/1MB) } elseif ($s -ge 1KB) { '{0:N2} KB' -f ($s/1KB) } else { \"$s Bytes\" }"
`) do set "result=%%R"

echo %result%
pause
Why PowerShell?

PowerShell natively supports 64-bit integers and floating-point arithmetic, and provides built-in size constants (1KB, 1MB, 1GB, 1TB) that make unit conversion trivial. The {0:N2} format string gives you two decimal places of precision, producing output like 1.50 GB instead of the truncated 1 GB that Batch would produce.

Capturing the Result

The for /f loop captures PowerShell's standard output into a Batch variable (result), allowing you to use the formatted string in subsequent Batch logic such as logging, report generation, or conditional alerts.

Conclusion

Converting bytes to human-readable units is a fundamental "Quality of Life" improvement for any system administration script. While native Batch math has hard limits at 2 GB, the logic itself is clean and efficient for everyday file management. By combining the native approach for small files with the PowerShell bridge for large ones, you build a robust, professional-grade reporting tool that works across all file sizes.