Converting NSData to int

Pranav Jaiswal picture Pranav Jaiswal · Sep 7, 2011 · Viewed 30.9k times · Source

I've an NSData object, the length is 4 bytes .These four bytes i'm extracting from another NSData object using ,

fourByteData=[completeData subdataWithRange:NSMakeRange(0, 16)];

My first question is, will the above statement provide me the first four bytes of complete data.

If Yes, then how to convert all these bytes to an equivalent int.

Answer

zaph picture zaph · Sep 7, 2011

Is 268566528 the value you expect or perhaps you expect 528? If the correct value is 528 then the byte order is big-endian but the cpu is little-endian, the bytes need to be reversed.

So, if the correct value should be 528 then:

NSData *data4 = [completeData subdataWithRange:NSMakeRange(0, 4)];
int value = CFSwapInt32BigToHost(*(int*)([data4 bytes]));

Also note that network standard order is big-endian.