6 * Cheesy number->string conversion, complete with carry rounding error.
8 char *num2str(unsigned long num, int maxlen, int base, int pow2, int unit_base)
10 const char *postfix[] = { "", "K", "M", "G", "P", "E" };
11 const char *byte_postfix[] = { "", "B", "bit" };
12 const unsigned int thousand[] = { 1000, 1024 };
13 unsigned int modulo, decimals;
14 int byte_post_index = 0, post_index, carry = 0;
20 for (post_index = 0; base > 1; post_index++)
21 base /= thousand[!!pow2];
34 while (post_index < sizeof(postfix)) {
35 sprintf(tmp, "%lu", num);
36 if (strlen(tmp) <= maxlen)
39 modulo = num % thousand[!!pow2];
40 num /= thousand[!!pow2];
41 carry = modulo >= thousand[!!pow2] / 2;
47 sprintf(buf, "%lu%s%s", num, postfix[post_index],
48 byte_postfix[byte_post_index]);
52 sprintf(tmp, "%lu", num);
53 decimals = maxlen - strlen(tmp);
61 sprintf(tmp, "%u", modulo);
62 if (strlen(tmp) <= decimals - 1)
65 modulo = (modulo + 9) / 10;
68 sprintf(buf, "%lu.%u%s%s", num, modulo, postfix[post_index],
69 byte_postfix[byte_post_index]);