6 * Cheesy number->string conversion, complete with carry rounding error.
8 char *num2str(unsigned long num, int maxlen, int base, int pow2)
10 char postfix[] = { ' ', 'K', 'M', 'G', 'P', 'E' };
11 unsigned int thousand[] = { 1000, 1024 };
12 unsigned int modulo, decimals;
13 int post_index, carry = 0;
19 for (post_index = 0; base > 1; post_index++)
20 base /= thousand[!!pow2];
23 while (post_index < sizeof(postfix)) {
24 sprintf(tmp, "%lu", num);
25 if (strlen(tmp) <= maxlen)
28 modulo = num % thousand[!!pow2];
29 num /= thousand[!!pow2];
30 carry = modulo >= thousand[!!pow2] / 2;
36 sprintf(buf, "%lu%c", num, postfix[post_index]);
40 sprintf(tmp, "%lu", num);
41 decimals = maxlen - strlen(tmp);
49 sprintf(tmp, "%u", modulo);
50 if (strlen(tmp) <= decimals - 1)
53 modulo = (modulo + 9) / 10;
56 sprintf(buf, "%lu.%u%c", num, modulo, postfix[post_index]);