Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C How to convert NSData to an array of ints?

I have a NSData item that is holding a bunch of ints. How do I go about getting them out and into an NSArray?

The memory structure in the NSData is 32-bit int in little-endian order, one right after the other.

Sorry for the basic question, but still learning the obj-c way of doing things :)

like image 944
Justin808 Avatar asked Feb 01 '11 06:02

Justin808


2 Answers

You can use the functions defined in OSByteOrder.h to deal with endianness. Aside from that quirk, this is really just a matter of grabbing the byte buffer and iterating over it.

// returns an NSArray containing NSNumbers from an NSData
// the NSData contains a series of 32-bit little-endian ints
NSArray *arrayFromData(NSData *data) {
    void *bytes = [data bytes];
    NSMutableArray *ary = [NSMutableArray array];
    for (NSUInteger i = 0; i < [data length]; i += sizeof(int32_t)) {
        int32_t elem = OSReadLittleInt32(bytes, i);
        [ary addObject:[NSNumber numberWithInt:elem]];
    }
    return ary;
}
like image 142
Lily Ballard Avatar answered Oct 24 '22 16:10

Lily Ballard


Sounds like there are cleaner ways to do what you're trying to do, but this should work:

NSData *data = ...; // Initialized earlier
int *values = [data bytes], cnt = [data length]/sizeof(int);
for (int i = 0; i < cnt; ++i)
  NSLog(@"%d\n", values[i]);
like image 37
yan Avatar answered Oct 24 '22 16:10

yan