开发者

iPhone SDK equivalent to C#'s BitConverter.GetBytes() and BitConverter.ToInt32()

开发者 https://www.devze.com 2023-02-12 08:50 出处:网络
I have a fairly simple questions and that is how can i get bytes from NSNumber and convert them back to NSNumber. So basically 开发者_如何转开发what I\'m looking for is Objective-c\'s equivalent of C#

I have a fairly simple questions and that is how can i get bytes from NSNumber and convert them back to NSNumber. So basically 开发者_如何转开发what I'm looking for is Objective-c's equivalent of C#'s Bitconverter.GetBytes() and BitConverter.ToInt32(startIndex, length)

I've spent quiet some time searcihg the web but haven't really found what I was looking for so I would really appreciate any kind of help.

Thanks


An NSNumber may contain an int, float, double, bool or a bunch of other things. So a binary version needs to store type and value. Which means that you want to archive (or, if you prefer, serialise) it. With that in mind, you're interested in the NSCoding protocol.

NSNumber responds to NSCoding so you can use the following:

NSNumber *aNumber = ...wherever this comes from...;
NSData *dataBlob = [NSKeyedArchiver archivedDataWithRootObject:aNumber];

/* and, later; this will return an autoreleased object so you quite possibly want
   to retain it */
NSNumber *number = [NSKeyedUnarchiver unarchiveObjectWithData:dataBlob];

See Ramhound's answer for specifics on getting C primitive access to the binary stuff contained in an NSData. The most relevant properties are length and bytes, and you'll possibly also be interested in +dataWithBytes:length: to create a new NSData from C primitives.

There are no guarantees about how long the binary data will be or what encoding it will use. You'd be better asking NSNumber for its contents in a particular format (e.g. [number intValue]), storing that to a C primitive and using the pointer to that if you're working on that sort of level.


What are you trying to accomplish? Objective-C objects don't usually give you access to their binary data directly, usually there is no reason to unless you are trying to serialize the objects out to a file on disk.

NSNumber doesn't expose this, you can ask for a value from it (i.e. floatValue, doubleValue, etc.) but you don't have direct access to the bytes themselves not unless you use NSKeyedArchivers archivedDataWithRootObject method.

0

精彩评论

暂无评论...
验证码 换一张
取 消