X-Git-Url: https://git.kernel.dk/?a=blobdiff_plain;f=lib%2Fnum2str.c;h=a1041926c5e5aff50dc540227a89d9d76d17dfc6;hb=17e3531ad6dcd6d0d8f1191f7fe484a345f26f52;hp=e114cdf8ebea83db1d79725403475f977b7d7cc9;hpb=1ec3d69b0ed8cc7a3eba0192685034d5442989e4;p=fio.git diff --git a/lib/num2str.c b/lib/num2str.c index e114cdf8..a1041926 100644 --- a/lib/num2str.c +++ b/lib/num2str.c @@ -5,13 +5,14 @@ /* * Cheesy number->string conversion, complete with carry rounding error. */ -char *num2str(unsigned long num, int maxlen, int base, int pow2) +char *num2str(unsigned long num, int maxlen, int base, int pow2, int unit_base) { - char postfix[] = { ' ', 'K', 'M', 'G', 'P', 'E' }; - unsigned int thousand[] = { 1000, 1024 }; + const char *postfix[] = { "", "K", "M", "G", "P", "E" }; + const char *byte_postfix[] = { "", "B", "bit" }; + const unsigned int thousand[] = { 1000, 1024 }; unsigned int modulo, decimals; - int post_index; - char tmp[32], fmt[8]; + int byte_post_index = 0, post_index, carry = 0; + char tmp[32]; char *buf; buf = malloc(128); @@ -19,6 +20,16 @@ char *num2str(unsigned long num, int maxlen, int base, int pow2) for (post_index = 0; base > 1; post_index++) base /= thousand[!!pow2]; + switch (unit_base) { + case 1: + byte_post_index = 2; + num *= 8; + break; + case 8: + byte_post_index = 1; + break; + } + modulo = -1U; while (post_index < sizeof(postfix)) { sprintf(tmp, "%lu", num); @@ -27,22 +38,34 @@ char *num2str(unsigned long num, int maxlen, int base, int pow2) modulo = num % thousand[!!pow2]; num /= thousand[!!pow2]; + carry = modulo >= thousand[!!pow2] / 2; post_index++; } if (modulo == -1U) { done: - sprintf(buf, "%lu%c", num, postfix[post_index]); + sprintf(buf, "%lu%s%s", num, postfix[post_index], + byte_postfix[byte_post_index]); return buf; } sprintf(tmp, "%lu", num); decimals = maxlen - strlen(tmp); - if (decimals <= 1) + if (decimals <= 1) { + if (carry) + num++; goto done; + } + + do { + sprintf(tmp, "%u", modulo); + if (strlen(tmp) <= decimals - 1) + break; + + modulo = (modulo + 9) / 10; + } while (1); - sprintf(fmt, "%%.%uu", decimals - 1); - sprintf(tmp, fmt, modulo); - sprintf(buf, "%lu.%s%c", num, tmp, postfix[post_index]); + sprintf(buf, "%lu.%u%s%s", num, modulo, postfix[post_index], + byte_postfix[byte_post_index]); return buf; }