From 4419844a889e14a9d7b08205a41b7d97fe4b2bfc Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Sat, 29 Jan 2005 18:19:44 +0000 Subject: [PATCH] Add print_human_readable_size() function. --- src/lib/stdio.c | 18 ++++++++++++++++++ src/lib/stdio.h | 1 + 2 files changed, 19 insertions(+) diff --git a/src/lib/stdio.c b/src/lib/stdio.c index 98b6303..3549d4e 100644 --- a/src/lib/stdio.c +++ b/src/lib/stdio.c @@ -608,3 +608,21 @@ hex_dump (uintptr_t ofs, const void *buf_, size_t size, bool ascii) size -= n; } } + +/* Prints SIZE, which represents a number of bytes, in a + human-readable format, e.g. "256 kB". */ +void +print_human_readable_size (uint64_t size) +{ + if (size == 1) + printf ("1 byte"); + else + { + static const char *factors[] = {"bytes", "kB", "MB", "GB", "TB", NULL}; + const char **fp; + + for (fp = factors; size >= 1024 && fp[1] != NULL; fp++) + size /= 1024; + printf ("%"PRIu64" %s", *fp); + } +} diff --git a/src/lib/stdio.h b/src/lib/stdio.h index 31be6d8..dc6ec35 100644 --- a/src/lib/stdio.h +++ b/src/lib/stdio.h @@ -28,6 +28,7 @@ int hprintf (int, const char *, ...) PRINTF_FORMAT (2, 3); int vhprintf (int, const char *, va_list) PRINTF_FORMAT (2, 0); #endif void hex_dump (uintptr_t ofs, const void *, size_t size, bool ascii); +void print_human_readable_size (uint64_t size); /* Internal functions. */ void __vprintf (const char *format, va_list args, -- 2.30.2