Converting NSData to int Converting NSData to int objective-c objective-c

Converting NSData to int


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.


That statement would give you the first 16 bytes of data, not 4. To get the first 4 bytes you need to modify your statement to:

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

To read the data from the NSData Object to an integer you could do something like:

int theInteger;[completeData getBytes:&theInteger length:sizeof(theInteger)];

You do not need to get the first 4 bytes if you are just converting it to an integer. You can do this directly from the two lines above and your completeData receiver


No you will get 16 bytes of data, since the range is from offset 0 and then 16 bytes.

If you had a NSData instance with 4 bytes then you could do a simple type cast like this:

int value = *(int*)([data bytes]);