0

I would like to transform NSData to int in Objective-c.

In the following code, "index2" is "15", but "value" is "0". (NSLog says "15,0".)

To be exact, "value" must be "15".

 NSString *index = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 NSString *index2 = [index stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
 int value = [index2 intValue];
 NSLog(@"%@,%d",index2,value);

Could you tell me how to solve this problem?

supermonkey
  • 631
  • 11
  • 25

1 Answers1

2

If you want to simply convert nsdata to int try the following.

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

Check this link you might need to read the NSData using a range.

Community
  • 1
  • 1
Tamil
  • 1,173
  • 1
  • 13
  • 35
  • Thank you for your reply. However I can't. theInteger becomes -272647185. To be exact, it must be 15. – supermonkey Aug 26 '14 at 14:45
  • Thanks. I don't understand that NSString index1 is '15', however int index2 is not 15 but 0. Why does [transforming NSString to int] go wrong? – supermonkey Aug 26 '14 at 18:12