James Raitsev
James Raitsev

Reputation: 96391

How to get an ascii value of a NSString*, pointing to a character?

When presented with an @"a", i'd like to be able to get it's ascii value of 97.

I thought this does it

NSString *c = [[NSString alloc] initWithString:@"a"];
NSLog(@"%d", [c intValue]); // Prints 0, expected 97

But ... you guessed it (or knew it :)) .. it does not.

How can i get an ascii value of a NSString*, pointing to a single character?

Upvotes: 6

Views: 3886

Answers (2)

0x8badf00d
0x8badf00d

Reputation: 6401

NSLog(@"%d",[c characterAtIndex:0]);

NSString class reference: The integer value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns INT_MAX or INT_MIN on overflow. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.

So it returned 0 because you called intValue on invalid decimal text representation of a number.

Upvotes: 4

Bourne
Bourne

Reputation: 10302

NSString *str = @"a";
unichar chr = [str characterAtIndex:0];
NSLog(@"ascii value %d", chr);

And why your method does not work is because you are operating on a STRING remember? Not a single character. Its still a NSString.

Upvotes: 6

Related Questions