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; +}