8 * num2str() - Cheesy number->string conversion, complete with carry rounding error.
9 * @num: quantity (e.g., number of blocks, bytes or bits)
10 * @maxlen: max number of digits in the output string (not counting prefix and units)
11 * @base: multiplier for num (e.g., if num represents Ki, use 1024)
12 * @pow2: select unit prefix - 0=power-of-10 decimal SI, nonzero=power-of-2 binary IEC
13 * @units: select units - N2S_* macros defined in fio.h
14 * @returns a malloc'd buffer containing "number[<unit prefix>][<units>]"
16 char *num2str(uint64_t num, int maxlen, int base, int pow2, int units)
18 const char *sistr[] = { "", "k", "M", "G", "T", "P" };
19 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
20 const char **unitprefix;
21 const char *unitstr[] = { "", "/s", "B", "bit", "B/s", "bit/s" };
22 const unsigned int thousand[] = { 1000, 1024 };
23 unsigned int modulo, decimals;
24 int unit_index = 0, post_index, carry = 0;
28 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
39 for (post_index = 0; base > 1; post_index++)
40 base /= thousand[!!pow2];
63 while (post_index < sizeof(sistr)) {
64 sprintf(tmp, "%llu", (unsigned long long) num);
65 if (strlen(tmp) <= maxlen)
68 modulo = num % thousand[!!pow2];
69 num /= thousand[!!pow2];
70 carry = modulo >= thousand[!!pow2] / 2;
76 if (post_index >= ARRAY_SIZE(sistr))
79 sprintf(buf, "%llu%s%s", (unsigned long long) num,
80 unitprefix[post_index], unitstr[unit_index]);
84 sprintf(tmp, "%llu", (unsigned long long) num);
85 decimals = maxlen - strlen(tmp);
93 sprintf(tmp, "%u", modulo);
94 if (strlen(tmp) <= decimals - 1)
97 modulo = (modulo + 9) / 10;
100 sprintf(buf, "%llu.%u%s%s", (unsigned long long) num, modulo,
101 unitprefix[post_index], unitstr[unit_index]);