2cb887563c534c777a17d9bd936cf01ee2f57def
[oweals/busybox.git] / libbb / human_readable.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * make_human_readable_str
4  *
5  * Copyright (C) 1999-2001 Erik Andersen <andersee@debian.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */
21
22 #include <stdio.h>
23 #include "libbb.h"
24
25
26
27 const char *make_human_readable_str(unsigned long size, 
28                 unsigned long block_size, unsigned long display_unit)
29 {
30         static char str[10] = "\0";
31         static const char strings[] = { 0, 'k', 'M', 'G', 'T', 0 };
32
33         if(size == 0 || block_size == 0)
34                 return("0");
35         
36         if(display_unit) {
37                 snprintf(str, 9, "%ld", (size/display_unit)*block_size);
38         } else {
39                 /* Ok, looks like they want us to autoscale */
40                 int i=0;
41                 unsigned long divisor = 1;
42                 long double result = size*block_size;
43                 for(i=0; i <= 4; i++) {
44                         divisor<<=10;
45                         if (result <= divisor) {
46                                 divisor>>=10;
47                                 break;
48                         }
49                 }
50                 result/=divisor;
51                 if (result > 10)
52                         snprintf(str, 9, "%.0Lf%c", result, strings[i]);
53                 else
54                         snprintf(str, 9, "%.1Lf%c", result, strings[i]);
55         }
56         return(str);
57 }
58
59 /* END CODE */
60 /*
61 Local Variables:
62 c-file-style: "linux"
63 c-basic-offset: 4
64 tab-width: 4
65 End:
66 */