tags:

views:

59

answers:

2

Hello,

I have a switch case like this

switch($filesize_in_bytes){
    case "10Mb <= $filesize_in_bytes <= 100Mb":
        //do some stuff and break;

    case "1Gb <= $filesize_in_bytes <= 10Gb":
        //do some stuff and break;
}

As you can see $filesize_in_bytes is in bytes, now how can I convert those values with Mbs and Gbs into bytes? The cases 10Mb, 100Mb, 1Gb and so on I cant hardcode them directly to bytes and the values too are different based on user status.

The case are fetched from database:

$rule1[0] = '10Mb';
$rule1[1] = '100Mb';

$rule2[0] = '1Gb';
$rule2[1] = '10Gb';
A: 

Take a look at the following PHP script that provides a function to do exactly this:

http://aidanlister.com/2004/04/human-readable-file-sizes/

ar
That's bytes => gb. The OP asked for gb => bytes. Not exactly what was asked for.
Frank Farmer
+1  A: 

First off, I don't really like this database design. So as not to waste space on byte-level precision by actually storing the limit as an integer (that would require a full BIGINT for things like 100Gb), you might want to instead do something like limit_amount INT UNSIGNED and limit_unit ENUM('b','kb','Mb','Gb'). Then when pulling from the database, you can just do simple math to get the byte value:

$limit_amount = 10; // pull from
$limit_unit = 'Mb'; // database
$units = array('b' => 1, 'kb' => 125, 'Mb' => 125000, 'Gb' => 125000000);
$limit_in_bytes = $limit_amount * $units[$limit_unit];

(Note that this system of units uses kb and Mb, which are different from kB and MB, the more common units. If you wanted the latter, make the proper conversions!)

That's much more data-efficient than storing as strings, ensures that your users can't put in nonsense units like "5lolCats" when inputting strings, and makes it easy to pull the data back to bytes.

...or you can just use BIGINT. I don't really mind, so as long as you're not storing integer values as strings.

Tahdah. You have pulled the amount from the database as bytes instead of a string, and now you can do a direct integer comparison without magic string compare weirdness.

Matchu
+1, but why is a kb 125 bytes? :p
Frank Farmer
@Frank Farmer: 1 kB is 1000 bytes. 1 kb is 125 bytes. Similarly, Mb != MB, and Gb != GB. I used the scale the OP was working with.
Matchu
The terminology in this domain is used very inconsistently, but you are technically correct -- 125 bytes = 1000 bits = 1 kilobit, 128 bytes = 1024 bits = 1 kibibit. However, when most people use any variant of "kb", they mean 1 kibibyte = 1024 bytes -- I'm fairly certain this was the OP's intent, even though he used ambiguous (and technically incorrect) terminology.
Frank Farmer
Added note to that effect, if OP will notice it. Notice, OP! :D
Matchu