8 * Cheesy number->string conversion, complete with carry rounding error.
10 char *num2str(unsigned long num, int maxlen, int base, int pow2, int unit_base)
12 const char *postfix[] = { "", "K", "M", "G", "P", "E" };
13 const char *byte_postfix[] = { "", "B", "bit" };
14 const unsigned int thousand[] = { 1000, 1024 };
15 unsigned int modulo, decimals;
16 int byte_post_index = 0, post_index, carry = 0;
22 for (post_index = 0; base > 1; post_index++)
23 base /= thousand[!!pow2];
36 while (post_index < sizeof(postfix)) {
37 sprintf(tmp, "%lu", num);
38 if (strlen(tmp) <= maxlen)
41 modulo = num % thousand[!!pow2];
42 num /= thousand[!!pow2];
43 carry = modulo >= thousand[!!pow2] / 2;
49 sprintf(buf, "%lu%s%s", num, postfix[post_index],
50 byte_postfix[byte_post_index]);
54 sprintf(tmp, "%lu", num);
55 decimals = maxlen - strlen(tmp);
63 sprintf(tmp, "%u", modulo);
64 if (strlen(tmp) <= decimals - 1)
67 modulo = (modulo + 9) / 10;
70 sprintf(buf, "%lu.%u%s%s", num, modulo, postfix[post_index],
71 byte_postfix[byte_post_index]);