rust 19 lines · 5 steps

Formatting byte counts as human-readable sizes

A Rust function that turns a raw byte count into a compact string like 2.5 MiB using bit tricks to pick the right unit.

Explained by highlit
1pub fn format_size(bytes: u64) -> String {
2 const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
3 
4 if bytes < 1024 {
5 return format!("{bytes} B");
6 }
7 
8 let exponent = (63 - bytes.leading_zeros()) / 10;
9 let exponent = exponent.min(UNITS.len() as u32 - 1);
10 let value = bytes as f64 / 1024_f64.powi(exponent as i32);
11 
12 if value >= 100.0 {
13 format!("{:.0} {}", value, UNITS[exponent as usize])
14 } else if value >= 10.0 {
15 format!("{:.1} {}", value, UNITS[exponent as usize])
16 } else {
17 format!("{:.2} {}", value, UNITS[exponent as usize])
18 }
19}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The base-2 log of a number equals its highest set bit position, which leading_zeros gives you for free.
  2. 2Dividing by 1024 raised to that exponent scales any byte count into its natural unit.
  3. 3Varying decimal precision by magnitude keeps output width roughly constant and readable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Formatting byte counts as human-readable sizes — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code