Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

ios - 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.

question from:https://stackoverflow.com/questions/13810204/convert-nsdata-length-from-bytes-to-megs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...