From a3b08eb5e53600356fd0fb0fbdf38607b75707bd Mon Sep 17 00:00:00 2001 From: leitner Date: Fri, 25 Apr 2003 19:06:19 +0000 Subject: [PATCH] add fmt_human and fmt_humank --- CHANGES | 1 + fmt.h | 6 ++++++ fmt/fmt_human.c | 26 ++++++++++++++++++++++++++ fmt/fmt_humank.c | 26 ++++++++++++++++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 fmt/fmt_human.c create mode 100644 fmt/fmt_humank.c diff --git a/CHANGES b/CHANGES index dd9800f..2375164 100644 --- a/CHANGES +++ b/CHANGES @@ -11,6 +11,7 @@ fix typos in several man pages (Hynek Schlawack) add stralloc versions of textcode API (Kai Ruemmler) add html to textcode ('<' to '<' etc) + add fmt_human and fmt_humank (format numbers ala ls -H/-h) 0.14: avoid bus errors in byte_copy diff --git a/fmt.h b/fmt.h index fc63663..9a41c69 100644 --- a/fmt.h +++ b/fmt.h @@ -69,4 +69,10 @@ unsigned int fmt_pad(char* dest,const char* src,unsigned int srclen,unsigned int * characters written. */ unsigned int fmt_fill(char* dest,unsigned int srclen,unsigned int padlen,unsigned int maxlen); +/* 1 -> "1", 4900 -> "4.9k", 2300000 -> "2.3M" */ +unsigned int fmt_human(char* dest,unsigned long long l); + +/* 1 -> "1", 4900 -> "4.8k", 2300000 -> "2.2M" */ +unsigned int fmt_humank(char* dest,unsigned long long l); + #endif diff --git a/fmt/fmt_human.c b/fmt/fmt_human.c new file mode 100644 index 0000000..6c0d085 --- /dev/null +++ b/fmt/fmt_human.c @@ -0,0 +1,26 @@ +#include "fmt.h" + +unsigned int fmt_human(char* dest,unsigned long long l) { + char unit; + int i; + if (l<1000) return fmt_ulong(dest,l); + if (l>1000000000000ull) { + l=(l+50000000000ull)/100000000000ull; + unit='T'; + } else if (l>1000000000) { + l=(l+50000000)/100000000; + unit='G'; + } else if (l>1000000) { + l=(l+50000)/100000; + unit='M'; + } else if (l>1000) { + l=(l+50)/100; + unit='k'; + } + if (!dest) return fmt_ulong(0,l)+2; + i=fmt_ulong(dest,l/10); + dest[i]='.'; + dest[i+1]=(l%10)+'0'; + dest[i+2]=unit; + return i+3; +} diff --git a/fmt/fmt_humank.c b/fmt/fmt_humank.c new file mode 100644 index 0000000..02623d9 --- /dev/null +++ b/fmt/fmt_humank.c @@ -0,0 +1,26 @@ +#include "fmt.h" + +unsigned int fmt_humank(char* dest,unsigned long long l) { + char unit; + int i; + if (l<1000) return fmt_ulong(dest,l); + if (l>1024*1024*1024*1024ull) { + l=(l+(1024*1024*1024*1024ull/20))/(1024*1024*1024*1024ull/10); + unit='T'; + } else if (l>1024*1024*1024) { + l=(l+(1024*1024*1024/20))/(1024*1024*1024/10); + unit='G'; + } else if (l>1024*1024) { + l=(l+(1024*1024/20))/(1024*1024/10); + unit='M'; + } else if (l>1024) { + l=(l+(1024/20))/(1024/10); + unit='k'; + } + if (!dest) return fmt_ulong(0,l)+2; + i=fmt_ulong(dest,l/10); + dest[i]='.'; + dest[i+1]=(l%10)+'0'; + dest[i+2]=unit; + return i+3; +}