Archive

Posts Tagged ‘kilobytes’

File sizes for humans (PHP, C, C++)

October 11, 2013 No comments

When we get a file size, we usually get it in bytes. It’s ok to have this value, but, when giving the user this information, we must convert it to another unit to make it a little more accessible. When talking about megabytes or gigabytes, everyone will make a mess. So here are some snippets to help us do that:

First in PHP:

1
2
3
4
5
6
7
8
9
function human_size ($tam) {
        $i = 0;
        $unids=array("bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb");
        while ($tam>1024) {
                $tam = $tam /1024;
                $i++;
        }
        return number_format($tam,2,",",".").$unids[$i];
}

So we can call:

1
echo human_size(12939128332323);

It will return

11.77Tb

So we can have (as users) a better value.

In C++ we can do it that way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <sstream>

using namespace std;

string human_size(long double size)
{
  static string units[10]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};
  ostringstream out;
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  out.precision(3);
  out<<size<<units[i];
  return out.str();
}

int main()
{
  cout <<human_size(1232312333)<<endl;
}

This time we use ostringstream to build the output string, but the basis is the same as php, it’s only to have a copy-paste snippet :)

And finally, C language, this time, we don’t have a string type, so we have to use char arrays to make it possible, this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

char *human_size(char *store, long double size)
{
  static char units[10][6]={"bytes","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb","Bb"};  
  int i= 0;

  while (size>1024) {
    size = size /1024;
    i++;
  }

  sprintf(store,"%.2Lf%s",size, units[i]);

  return store;
}

int main()
{
  char cadena[30];
  printf("Size: %s\n", human_size(cadena, 1293323872));
}

I know I’m using a lot of units: “bytes”, “Kilobytes”, “Megabytes”, “GigaBytes”, “Terabytes”, “Petabytes”, “Exabytes”, “Zetabytes”, “Yottabytes” and “Brontobytes”, and numeric variables won’t store such huge numbers. :)

This post is available in Spanish here: http://totaki.com/poesiabinaria/2010/03/tamano-de-archivo-para-seres-humanos-phpc-y-c/
Photo: Kate Haskell (Flickr) CC-by

Top