views:

65

answers:

2

for example:

NSString *foo = @"a";

How can I get the ASCII value of this? (I know it is really 97, but how can I get it using Objective-C?)

I guess I can convert it to char but I had no luck with that so far. Sorry for being too nooby!

A: 

Hi,

you can try this (untested code)

NSString *field = @"s";

unichar c = [field characterAtIndex:0];
NSLog(@"decimal char %d", c);

and vice versa

unichar asciiChar = 65; // the character A; can also be written like 'A' or 0x0041
NSString *stringWithAsciiChar = [NSString stringWithCharacters:&asciiChar length:1];

hope it helps

regards

ReaperXmac
Wow! thanx a lot! Perfect answer, really!
Bash
While usually correct, this doesn't work too well with multi-byte languages (UTF16 and above encodings).
Dave DeLong
+1  A: 

You can get the character at a certain index using NSString's characterAtIndex. The result is a unichar which is an unsigned short. You can probably use this as the ASCII value by casting, although it is a unicode character.

31eee384