Version 3 of hrbytesize

Updated 2012-11-03 18:58:03 by naruto

MB In some interactive applications, like a file explorer for example, one must display a size in a human readable way, such as 39 MB for example, instead of the size in bytes (39 000 000 bytes in that specific case) which is directly return by the "file size" command. The problem also applies to memory allocation, where one computes what is the memory required by a matrix.

Doing the transformation is not a complicated task in decimal system, but is more tricky in binary, where one kilobyte is considered as 1024 bytes. Another problem to deal with is the management for large integers, that is, for files a problem which was addressed by the bigfloat Tcllib package in Tcl 8.4 and is now included in Tcl 8.5 core. The reverse operation is to take a string representing a size in a human-readable fashion and to put back into bytes.

The hrbytesize package in the Tclrep projet solves that easy problem :

http://tclrep.cvs.sourceforge.net/viewvc/tclrep/modules/hrbytesize/

The implementation in the Tclrep project is a re-design of the implementation I previously posted on the file size page. In its most basic usage a 10000000 integer, representing a size in bytes is converted into the string "10.0 MB" with the reduce method.

     set size1 [hrbytesize create %AUTO%]
     $size1 configure -size 10000000        
     $size1 reduce
     set hrsize [$size1 humanreadable]
     $size1 destroy

The reverse operation is done by the expand method.

In the following example, a 1.0 EiB size is expanded so that the size in bytes is computed. The power is 6 and the system is "binary". The expanded size is too long for my tired fingers...

     set mybytesize [hrbytesize create %AUTO%]
     $mybytesize configure -reducedsize 1.0
     $mybytesize configure -reducedunit EiB
     $mybytesize expand
     set power [$mybytesize cget -power]
     set unitsystem [$mybytesize cget -unitsystem]
     set size [$mybytesize cget -size]
     $mybytesize destroy

The core of expand and reduce methods is based on the bigfloat package. At the basis, one finds a map from the following human-readable units and the power of 1000 or 1024, which simply is the position of the unit in the list :

  • binary size units : "B" "KiB" "MiB" "GiB" "TiB" "PiB" "EiB",
  • decimal size units : "B" "KB" "MB" "GB" "TB" "PB" "EB".

The additionnal facilities "compare" and "comparehumanreadable" allows to compare two sizes in bytes or two sizes in a human-readable form.