Converting Unichar to Int Problem

fabian789 picture fabian789 · Nov 14, 2010 · Viewed 8.2k times · Source

I've got a strange problem trying to convert from unichar to int:

I have a String containing a few numbers, like @"12345". This numbers I want to save individually, meaning I want 5 numbers, 1, 2, 3, ... . Now, while

NSLog(@"Value: %C", [myString characterAtIndex:0]);

returns

Value: 1

This:

NSLog(@"Value: %@", [NSNumber numberWithUnsignedChar:[myString characterAtIndex:0]]);

returns

Value: 49

I would really appreciate some help, Fabian

Answer

Chris Parker picture Chris Parker · Nov 14, 2010

In the code above, you're getting exactly what you're asking for; the numeric value of the character '1' is 49, and you're creating an NSNumber from that.

If what you want is 1, then you can can take advantage of the fact that the digits 0-9 are laid out in order in the ASCII/UTF-8 tables and subtract an appropriate value from the unichar you receive.

Try out this code snippet to get you started in the right direction:

NSString *s = @"0123456789";
for (int i = 0; i < [s length]; i++) {
    NSLog(@"Value: %d", [s characterAtIndex:i]);
}