Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSData to int

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.

like image 255
Pranav Jaiswal Avatar asked Sep 07 '11 10:09

Pranav Jaiswal


2 Answers

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.

like image 196
zaph Avatar answered Nov 20 '22 11:11

zaph


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

like image 26
Suhail Patel Avatar answered Nov 20 '22 10:11

Suhail Patel