The following piece of code is supposed to return two integers: val1 = 2 and val2 = 5.
NSString *col = @"1245DD";
char c1 = [col characterAtIndex:1];
char c2 = [col characterAtIndex:3];
int val1 = [[[NSString alloc] initWithUTF8String:&c1] intValue];
int val2 = [[[NSString alloc] initWithUTF8String:&c2] intValue];
inspecting values at runtime:
-
c1 = ‘2’
-
c2 = ‘5’
good so far.
But then:
- val1 = 2
- val2 = 52
I don’t understand why val2 always ends up being the concatenation of c2 and c1. What am I missing?
thanks,
You are creating an
NSStringobject as a UTF-8 string, that is in fact a single character. You need to NUL-terminate the UTF-8 string if you want to use it like this.Note that
[NSString characterAtIndex:]returns aunichar, not achar, so use[NSString initWithCharacters:length:]instead where you can tell the method how many characters to use: