Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert NSData Length from bytes to megs

Tags:

ios

nsdata

nslog

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.

like image 745
HurkNburkS Avatar asked Dec 10 '12 22:12

HurkNburkS


People also ask

What is NSData?

NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.

What is NSMutableData?

An object representing a dynamic byte buffer in memory.


2 Answers

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

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

Mind you, this is a simplistic approach that couldn't really properly accommodate for byte sizes below 1,048,576 bytes or above 1,073,741,823 bytes. For a more complete solution that can handle varying file sizes, see: ObjC/Cocoa class for converting size to human-readable string?

Or for OS X 10.8+ and iOS 6+

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

In Swift:

print(ByteCountFormatter().string(fromByteCount: Int64(data.count))) 
like image 61
Mick MacCallum Avatar answered Sep 21 '22 15:09

Mick MacCallum


For Swift 3, in Mb:

let countBytes = ByteCountFormatter() countBytes.allowedUnits = [.useMB] countBytes.countStyle = .file let fileSize = countBytes.string(fromByteCount: Int64(dataToMeasure!.count))  print("File size: \(fileSize)") 
like image 20
Ber.to Avatar answered Sep 23 '22 15:09

Ber.to