logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

humanize.c (873B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include "../lib/humanize.h"
  6. #include <stdio.h> // snprintf
  7. struct si_scale
  8. dtosi(double num, bool iec)
  9. {
  10. #define PFX 11
  11. const char *si_prefixes[PFX] = {"", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"};
  12. const char *iec_prefixes[PFX] = {
  13. "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB"};
  14. int div = iec ? 1024 : 1000;
  15. const char **prefixes = iec ? iec_prefixes : si_prefixes;
  16. struct si_scale ret = {
  17. .number = num,
  18. .prefix = "",
  19. .exponant = 0,
  20. };
  21. while(ret.number > div && ret.exponant < PFX)
  22. {
  23. ret.number /= div;
  24. ret.exponant += 1;
  25. }
  26. ret.prefix = prefixes[ret.exponant];
  27. return ret;
  28. }