Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unichar to Int Problem

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

like image 636
fabian789 Avatar asked Nov 14 '10 18:11

fabian789


1 Answers

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]);
}
like image 136
Chris Parker Avatar answered Sep 30 '22 13:09

Chris Parker