7 #define ARRAY_LENGTH(arr) sizeof(arr) / sizeof((arr)[0])
10 * num2str() - Cheesy number->string conversion, complete with carry rounding error.
11 * @num: quantity (e.g., number of blocks, bytes or bits)
12 * @maxlen: max number of digits in the output string (not counting prefix and units)
13 * @base: multiplier for num (e.g., if num represents Ki, use 1024)
14 * @pow2: select unit prefix - 0=power-of-10 decimal SI, nonzero=power-of-2 binary IEC
15 * @units: select units - N2S_* macros defined in fio.h
16 * @returns a malloc'd buffer containing "number[<unit prefix>][<units>]"
18 char *num2str(uint64_t num, int maxlen, int base, int pow2, int units)
20 const char *sistr[] = { "", "k", "M", "G", "T", "P" };
21 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
22 const char **unitprefix;
23 const char *unitstr[] = { "", "/s", "B", "bit", "B/s", "bit/s" };
24 const unsigned int thousand[] = { 1000, 1024 };
25 unsigned int modulo, decimals;
26 int unit_index = 0, post_index, carry = 0;
30 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
41 for (post_index = 0; base > 1; post_index++)
42 base /= thousand[!!pow2];
65 while (post_index < sizeof(sistr)) {
66 sprintf(tmp, "%llu", (unsigned long long) num);
67 if (strlen(tmp) <= maxlen)
70 modulo = num % thousand[!!pow2];
71 num /= thousand[!!pow2];
72 carry = modulo >= thousand[!!pow2] / 2;
78 if (post_index >= ARRAY_LENGTH(sistr))
81 sprintf(buf, "%llu%s%s", (unsigned long long) num,
82 unitprefix[post_index], unitstr[unit_index]);
86 sprintf(tmp, "%llu", (unsigned long long) num);
87 decimals = maxlen - strlen(tmp);
95 sprintf(tmp, "%u", modulo);
96 if (strlen(tmp) <= decimals - 1)
99 modulo = (modulo + 9) / 10;
102 sprintf(buf, "%llu.%u%s%s", (unsigned long long) num, modulo,
103 unitprefix[post_index], unitstr[unit_index]);