Centurion
Centurion

Reputation: 14304

How to convert NSData bytes into NSNumber or NSInteger?

There's a special NSString initWithData method for grabbing bits and converting them into string. However, I haven't found that in NSNumber class ref. Currently, I'm getting raw data (bytes) from a server in NSData format. I know how to do that in C, using memcpy and int pointers. But I am curious about what the convenience methods are for doing that straight from NSData. No conversion is needed. For example, I'm getting 00000010 byte, and I need to turn that into NSNumber of value 2, or NSInteger.

Upvotes: 3

Views: 15309

Answers (4)

Elise van Looij
Elise van Looij

Reputation: 4232

NSString to the rescue:

const unsigned char *bytes = [serverData bytes];
NSInteger aValue = [NSString stringWithFormat:@"%2x", bytes[0]].integerValue;

The docs warn about using NSScanner for localized decimal numbers, but that's of no concern in this case.

Upvotes: 1

Jeevanantham Balusamy
Jeevanantham Balusamy

Reputation: 213

Here is the answer

//Integer to NSData
+(NSData *) IntToNSData:(NSInteger)data
{
    Byte *byteData = (Byte*)malloc(4);
    byteData[3] = data & 0xff;
    byteData[2] = (data & 0xff00) >> 8;
    byteData[1] = (data & 0xff0000) >> 16;
    byteData[0] = (data & 0xff000000) >> 24;
    NSData * result = [NSData dataWithBytes:byteData length:4];
    NSLog(@"result=%@",result);
    return (NSData*)result;
}

refer https://stackoverflow.com/a/20497490/562812 for more detail

Upvotes: -3

ikuramedia
ikuramedia

Reputation: 6058

NSData is just a bucket for bytes and has no knowledge of the data contained therein. NSString's initWithData:encoding: method is a reciprocal (it does the opposite) of this method:

- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding

Therefore, to answer your question fully, it's important to know how your numbers were originally coerced into an NSData object. Once you know the encoding function, the search is for the reciprocal function.

From what you've included in the question, there may be a number of different solutions. However, you'll probably be able to use something along the following lines to convert into a usable numeric format using getBytes:length: on your NSData object. For e.g.

NSUInteger decodedInteger;
[myDataObject getBytes:&decodedInteger length:sizeof(decodedInteger)];

You can change the type of decodedInteger to whatever is appropriate for the bytes in your NSData object.

Upvotes: 10

mbh
mbh

Reputation: 3312

Try this:

NSNumber *num = [NSKeyedUnarchiver unarchiveObjectWithData:numberAsNSData]; 

Edit:

As pointed out by Matthias Bauch this will not work in your case. This only works if your NSNumber object was archived into NSData objects.

Upvotes: 1

Related Questions