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_* constants 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, enum n2s_unit units)
22 const char *sistr[] = { "", "k", "M", "G", "T", "P" };
23 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
24 const char **unitprefix;
25 static const char *const unitstr[] = {
30 [N2S_BYTEPERSEC]= "B/s",
31 [N2S_BITPERSEC] = "bit/s"
33 const unsigned int thousand = pow2 ? 1024 : 1000;
35 int post_index, carry = 0;
36 char tmp[32], fmt[32];
39 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
40 assert(units < ARRAY_SIZE(unitstr));
51 for (post_index = 0; base > 1; post_index++)
72 * Divide by K/Ki until string length of num <= maxlen.
75 while (post_index < ARRAY_SIZE(sistr)) {
76 sprintf(tmp, "%llu", (unsigned long long) num);
77 if (strlen(tmp) <= maxlen)
80 modulo = num % thousand;
82 carry = modulo >= thousand / 2;
87 * If no modulo, then we're done.
91 if (post_index >= ARRAY_SIZE(sistr))
94 sprintf(buf, "%llu%s%s", (unsigned long long) num,
95 unitprefix[post_index], unitstr[units]);
100 * If no room for decimals, then we're done.
102 sprintf(tmp, "%llu", (unsigned long long) num);
103 if ((int)(maxlen - strlen(tmp)) <= 1) {
110 * Fill in everything and return the result.
112 assert(maxlen - strlen(tmp) - 1 > 0);
113 assert(modulo < thousand);
114 sprintf(fmt, "%%.%df", (int)(maxlen - strlen(tmp) - 1));
115 sprintf(tmp, fmt, (double)modulo / (double)thousand);
117 sprintf(buf, "%llu.%s%s%s", (unsigned long long) num, &tmp[2],
118 unitprefix[post_index], unitstr[units]);