Getting MBs


on page 155, we read the file size of the png we imported:

NSLog(@“The file read from the disk has %lu bytes”, [readData length]);

how do I convert the types into megabytes?

doesn’t seem to work. It seems like I need to get the result then divide by 1024, but I’m not sure how to do that at this stage.


If you’re confident everything is at least 1 MB in size, and you don’t mind rounding down (e.g., 1.9MB will round to 1MB) then this should work:

NSLog(@"The file read from the disk has %lu MB", [readData length] / 1024);

(Anything under 1MB will give you 0 MB, which definitely looks wrong even if it’s quasi-correct.)

If you’d like more precision, you can specify a float value and make sure the division results in a float (integer division gives integers):

NSLog(@"The file read from the disk has %0.1f MB", [readData length] / 1024.0);

%0.1f should constrain the number of digits following the decimal point to give you values like 1.3, 5.0, etc.


That works perfect. Thanks.


Interestingly, to get this to work you’ll need:

Note the 102400.0, not 1024.0. And then you get log like

The file read from the disk has 0.26 MB

Wouldn’t it be great to have a function that returns MB or kb or bytes depending on what the file size is?


OK, I made a mistake

26209 bytes = 25.59KB = 0.02499MB

each time divide by 1024. So 1024 times 2024 is 1048576.
26206 divided by 1048576 = 0.02499MB


Oops, yeah, sorry, didn’t think about the math, only the code.

Typically I’ll include all the factors in parentheses like this:

NSLog(@"The file read from the disk has %0.1f MB", [readData length] / (1024.0 * 1024));

If you had to do a lot of calculations along those lines, #define is handy:

#define B_TO_KB 1024.0
#define B_TO_MB 1024 * B_TO_KB
#define B_TO_GB 1024 * B_TO_MB

NSLog(@"The file read from the disk has %0.1f GB", [readData length] / B_TO_GB);


Small suggestion:

#define B_TO_MB 1024 * B_TO_KB
You should always put something like this in parentheses. Why?

What is do you think this is?

int x = B_TO_MB / B_TO_MB;
1, right? Nope.

If you expand the macro you get

int x = 1024 * 1024 / 1024 * 1024;
Which is evaluated from left to right. Which is 1,048,576.

#define B_TO_MB (1024 * B_TO_KB)


Good point, thanks. I recall there being a relatively famous example of the value of parens in the macro definition for MIN or MAX, but I’m drawing a blank at the moment.


Great reminder for the macros topic. Thanks macintux and Aaron