humanize.c (873B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include "../lib/humanize.h"
- #include <stdio.h> // snprintf
- struct si_scale
- dtosi(double num, bool iec)
- {
- #define PFX 11
- const char *si_prefixes[PFX] = {"", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"};
- const char *iec_prefixes[PFX] = {
- "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB"};
- int div = iec ? 1024 : 1000;
- const char **prefixes = iec ? iec_prefixes : si_prefixes;
- struct si_scale ret = {
- .number = num,
- .prefix = "",
- .exponent = 0,
- };
- while(ret.number > div && ret.exponent < PFX)
- {
- ret.number /= div;
- ret.exponent += 1;
- }
- ret.prefix = prefixes[ret.exponent];
- return ret;
- }