diff options
Diffstat (limited to 'lib/common/print_size.c')
-rw-r--r-- | lib/common/print_size.c | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/lib/common/print_size.c b/lib/common/print_size.c new file mode 100644 index 0000000..6e76805 --- /dev/null +++ b/lib/common/print_size.c @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* + * print_size.c + * + * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at> + */ +#include "config.h" +#include "common.h" + +void print_size(sqfs_u64 size, char *buffer, bool round_to_int) +{ + static const char *fractions = "0112334456678899"; + static const char *suffices = "kMGTPEZY"; + unsigned int fraction; + int suffix = -1; + + while (size > 1024) { + ++suffix; + fraction = size % 1024; + size /= 1024; + } + + if (suffix >= 0) { + fraction /= 64; + + if (round_to_int) { + size = fraction >= 8 ? (size + 1) : size; + + sprintf(buffer, "%u%c", (unsigned int)size, + suffices[suffix]); + } else { + sprintf(buffer, "%u.%c%c", (unsigned int)size, + fractions[fraction], suffices[suffix]); + } + } else { + sprintf(buffer, "%u", (unsigned int)size); + } +} |