6 #include "../compiler/compiler.h"
9 #define ARRAY_SIZE(x) (sizeof((x)) / (sizeof((x)[0])))
12 * num2str() - Cheesy number->string conversion, complete with carry rounding error.
13 * @num: quantity (e.g., number of blocks, bytes or bits)
14 * @maxlen: max number of digits in the output string (not counting prefix and units, but counting .)
15 * @base: multiplier for num (e.g., if num represents Ki, use 1024)
16 * @pow2: select unit prefix - 0=power-of-10 decimal SI, nonzero=power-of-2 binary IEC
17 * @units: select units - N2S_* macros defined in num2str.h
18 * @returns a malloc'd buffer containing "number[<unit prefix>][<units>]"
20 char *num2str(uint64_t num, int maxlen, int base, int pow2, int units)
22 const char *sistr[] = { "", "k", "M", "G", "T", "P" };
23 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
24 const char **unitprefix;
25 const char *unitstr[] = { "", "/s", "B", "bit", "B/s", "bit/s" };
26 const unsigned int thousand[] = { 1000, 1024 };
28 int unit_index = 0, post_index, carry = 0;
29 char tmp[32], fmt[32];
32 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
43 for (post_index = 0; base > 1; post_index++)
44 base /= thousand[!!pow2];
67 * Divide by K/Ki until string length of num <= maxlen.
70 while (post_index < sizeof(sistr)) {
71 sprintf(tmp, "%llu", (unsigned long long) num);
72 if (strlen(tmp) <= maxlen)
75 modulo = num % thousand[!!pow2];
76 num /= thousand[!!pow2];
77 carry = modulo >= thousand[!!pow2] / 2;
82 * If no modulo, then we're done.
86 if (post_index >= ARRAY_SIZE(sistr))
89 sprintf(buf, "%llu%s%s", (unsigned long long) num,
90 unitprefix[post_index], unitstr[unit_index]);
95 * If no room for decimals, then we're done.
97 sprintf(tmp, "%llu", (unsigned long long) num);
98 if ((int)(maxlen - strlen(tmp)) <= 1) {
105 * Fill in everything and return the result.
107 assert(maxlen - strlen(tmp) - 1 > 0);
108 assert(modulo < thousand[!!pow2]);
109 sprintf(fmt, "%%.%df", (int)(maxlen - strlen(tmp) - 1));
110 sprintf(tmp, fmt, (double)modulo / (double)thousand[!!pow2]);
112 sprintf(buf, "%llu.%s%s%s", (unsigned long long) num, &tmp[2],
113 unitprefix[post_index], unitstr[unit_index]);