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