7 #define ARRAY_LENGTH(arr) sizeof(arr) / sizeof((arr)[0])
10 * Cheesy number->string conversion, complete with carry rounding error.
12 char *num2str(uint64_t num, int maxlen, int base, int pow2, int unit_base)
14 const char *postfix[] = { "", "K", "M", "G", "P", "E" };
15 const char *byte_postfix[] = { "", "B", "bit" };
16 const unsigned int thousand[] = { 1000, 1024 };
17 unsigned int modulo, decimals;
18 int byte_post_index = 0, post_index, carry = 0;
24 for (post_index = 0; base > 1; post_index++)
25 base /= thousand[!!pow2];
38 while (post_index < sizeof(postfix)) {
39 sprintf(tmp, "%llu", (unsigned long long) num);
40 if (strlen(tmp) <= maxlen)
43 modulo = num % thousand[!!pow2];
44 num /= thousand[!!pow2];
45 carry = modulo >= thousand[!!pow2] / 2;
51 if (post_index >= ARRAY_LENGTH(postfix))
54 sprintf(buf, "%llu%s%s", (unsigned long long) num,
55 postfix[post_index], byte_postfix[byte_post_index]);
59 sprintf(tmp, "%llu", (unsigned long long) num);
60 decimals = maxlen - strlen(tmp);
68 sprintf(tmp, "%u", modulo);
69 if (strlen(tmp) <= decimals - 1)
72 modulo = (modulo + 9) / 10;
75 sprintf(buf, "%llu.%u%s%s", (unsigned long long) num, modulo,
76 postfix[post_index], byte_postfix[byte_post_index]);