Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd bug converting char to int (Objective C)

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?

like image 386
Greg Avatar asked Jun 22 '12 22:06

Greg


2 Answers

I figured it out: just convert it to NSString and then get the intValue.

[[NSString stringWithFormat:@"%c", thechar] intValue];
like image 144
Greg Avatar answered Oct 24 '22 12:10

Greg


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);
like image 40
dlev Avatar answered Oct 24 '22 12:10

dlev