I have an app set up where I convert an NSString into an array of char variables, and I'm trying to convert some of the chars to integers (basically to parse the numbers out of the string). But when I try to convert them to int variables, they suddenly change value.
For example:
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 (that I've found) of converting it seem to change the value to 51. Does anyone know what might be happening?
I figured it out: just convert it to NSString and then get the intValue.
[[NSString stringWithFormat:@"%c", thechar] intValue];
51 is the numeric value for the literal character '3'. It dates back to the ASCII standard, though many common Unicode encodings maintain the value as well.
You can pretty reliably just subtract 48 (or '0') to get the number:
int num = (int)(numAsChar - '0');
Alternatively, if you want to convert an entire string, you can use atoi:
int num = atoi(myNumberString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With