iosnsdatanslog

convert NSData Length from bytes to megs


I am trying to NSLog the number of megs my NSData object is however currently all I can get is bytes by using

NSLog(@"%u", myData.length);

So how would I change this NSLog statement so I can see something like

2.00 megs

any help would be appreciated.


Solution

  • There are 1000 bytes in a kilobyte and 1000 kilobytes in a megabyte, so...

    NSLog(@"File size is : %.2f MB",(float)myData.length/1000.0f/1000.0f);
    

    Mind you, this is a simplistic approach that doesn’t handle particularly large or small numbers. A more generalized solution is to use Apple’s NSByteCountFormatter:

    Or for OS X 10.8+ and iOS 6+

    NSLog(@"%@", [[NSByteCountFormatter new] stringFromByteCount:data.length]);
    

    In Swift:

    print(ByteCountFormatter().string(fromByteCount: Int64(data.count)))