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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The base-2 log of a number equals its highest set bit position, which leading_zeros gives you for free.
- 2Dividing by 1024 raised to that exponent scales any byte count into its natural unit.
- 3Varying decimal precision by magnitude keeps output width roughly constant and readable.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/formatting-byte-counts-as-human-readable-sizes-explained-rust-a01f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.