Odd conversion of char errors to int (Objective-C)

I have an application where I convert NSString to an array of char variables, and I'm trying to convert some of the characters to integers (mainly for parsing numbers from a string). But when I try to convert them to int variables, they suddenly change value.

For instance:

char thechar = array[7]; //to make sure the issue isn't related to the array NSLog(@"%c %i %i",thechar,(int) thechar, [[NSNumber numberWithUnsignedChar:thechar] intValue]); 

returns this:

 3 51 51 

Both methods (which I found) to convert it seem to change the value to 51. Does anyone know what might happen?

+4
source share
2 answers

I realized: just convert it to NSString and then get intValue.

 [[NSString stringWithFormat:@"%c", thechar] intValue]; 
+11
source

51 is the numeric value for the letter character '3'. It goes back to the ASCII standard, although many common Unicode encodings also support value.

You can pretty safely just subtract 48 (or '0') to get the number:

 int num = (int)(numAsChar - '0'); 

Alternatively, if you want to convert the whole string, you can use atoi :

 int num = atoi(myNumberString); 
+3
source

All Articles