diff options
author | Matt Kraai <kraai@debian.org> | 2001-03-28 20:42:27 +0400 |
---|---|---|
committer | Matt Kraai <kraai@debian.org> | 2001-03-28 20:42:27 +0400 |
commit | 7cd0cfeab696a4e5b2794dd66541b6d2a6cc3663 (patch) | |
tree | 8733711c52f6dd894aa6bf955b295aae5149aa8d /libbb/human_readable.c | |
parent | f957c779104d187a035b48d1fb9ce9acb7351001 (diff) |
Rewrite to fix bug #1140 and make it slightly smaller.
Diffstat (limited to 'libbb/human_readable.c')
-rw-r--r-- | libbb/human_readable.c | 40 |
1 files changed, 14 insertions, 26 deletions
diff --git a/libbb/human_readable.c b/libbb/human_readable.c index ff2175175..1d7a90e55 100644 --- a/libbb/human_readable.c +++ b/libbb/human_readable.c @@ -28,35 +28,23 @@ #include <stdio.h> #include "libbb.h" - +static char buffer[10]; +static const char *suffixes[] = { "", "k", "M", "G", "T" }; const char *make_human_readable_str(unsigned long val, unsigned long hr) { - int i=0; - static char str[10] = "\0"; - static const char strings[] = { 'k', 'M', 'G', 'T', 0 }; - unsigned long divisor = 1; + int suffix, base; - if(val == 0) - return("0"); - if(hr) - snprintf(str, 9, "%ld", val/hr); - else { - while(val >= divisor && i <= 4) { - divisor=divisor<<10, i++; - } - divisor=divisor>>10, i--; - snprintf(str, 9, "%.1Lf%c", (long double)(val)/divisor, strings[i]); + for (suffix = 0, base = 1; suffix < 5; suffix++, base <<= 10) { + if (val < (base << 10)) { + if (suffix && val < 10 * base) + sprintf(buffer, "%lu.%lu%s", val / base, + (val % base) * 10 / base, suffixes[suffix]); + else + sprintf(buffer, "%lu%s", val / base, suffixes[suffix]); + break; + } } - return(str); -} - -/* END CODE */ -/* -Local Variables: -c-file-style: "linux" -c-basic-offset: 4 -tab-width: 4 -End: -*/ + return buffer; +} |