Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

content-length conversion

I'm checking file-size using a script that report content-length in BYTES that matches exactly what I see on my Mac, BUT if I convert bytes to KBs:

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
}

... the size in KB is always different than what I see on my Mac.

So example:

Windows 8 TV Ad Tune.m4r

  • Bytes (Mac): 4,27,840 bytes
  • KBs (Mac) : 428KB

  • Bytes (Script): 427840

  • KBs (Script): 417.81 KB

I wonder if its the script or something else causing this difference?

Thanks!

like image 369
eozzy Avatar asked Sep 15 '25 20:09

eozzy


2 Answers

It looks like the Mac is using the 1000 convention, i.e. that 1kB is 1000 bytes. Your conversion is using 1kB = 1024 bytes. Both are technically correct, however most programmers will use 1kB = 1024. Mac uses 1kB = 1000, and Windows uses 1kB = 1024.

Hard drive manufacturers will use the 1000 convention so they can use bigger numbers when advertising, which is why my 1 terabyte hard drive I have installed on my machine is listed as only having 931 gigabytes in Windows.

My recommendation when checking file sizes in code is to always use bytes, as this will avoid this discrepancy and also be more portable.

like image 102
Bok McDonagh Avatar answered Sep 19 '25 01:09

Bok McDonagh


Maybe you are comparing size on disk (on Mac) and your script size conversion. The size on disk depend of your hard drive partition bloc size.

If the true size is 417.81 KBs and your bloc size is 200 KBs (this is not a real example) so your size on disk will be 600 KBs.

Size on disk is not the real size of you file, but the size occupied by your file on the disk.

Hope this may help.

like image 25
Blackarma Avatar answered Sep 19 '25 01:09

Blackarma