How to convert ASCII value to a character in Objective-C?

topace picture topace · May 14, 2010 · Viewed 49.1k times · Source

I was wondering if anyone has the following php function equivalents in Objective-C for iPhone development:

  1. ord() # returns the ASCII value of the first character of a string.
  2. chr() # returns a character from the specified ASCII value.

Many thanks!

Answer

alleus picture alleus · May 14, 2010

This is how you can work with ASCII values and NSString. Note that since NSString is working with unichars, there could be unexpected results for a non ASCII string.

// NSString to ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65

// ASCII to NSString
int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A