title: Base 62 conversion in Objective-C
body: <p>I spent much too much time trying to find an implementation for base 62 conversion for Objective-C. I am sure this is a terrible example and there must be an elegant, super-efficient way to do this, but this works, please edit or answer to improve it! But I wanted to help people searching for this to have something that will work. There doesn't appear to be anything specific to be found for an Objective-C implementation. </p>
  
  <pre><code>@implementation Base62Converter
  
  +(int)decode:(NSString*)string
  {
      int num = 0;
      NSString * alphabet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  
      for (int i = 0, len = [string length]; i &lt; len; i++)
      {
          NSRange range = [alphabet rangeOfString:[string substringWithRange:NSMakeRange(i,1)]];
          num = num * 62 + range.location;
      }
  
      return num;
  }
  
  +(NSString*)encode:(int)num
  {
      NSString * alphabet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      NSMutableString * precursor = [NSMutableString stringWithCapacity:3];
  
      while (num &gt; 0)
      {
          [precursor appendString:[alphabet substringWithRange:NSMakeRange( num % 62, 1 )]];
          num /= 62;
      }
  
      // http://stackoverflow.com/questions/6720191/reverse-nsstring-text
      NSMutableString *reversedString = [NSMutableString stringWithCapacity:[precursor length]];
  
      [precursor enumerateSubstringsInRange:NSMakeRange(0,[precursor length])
                               options:(NSStringEnumerationReverse |NSStringEnumerationByComposedCharacterSequences)
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                [reversedString appendString:substring];
                            }];
      return reversedString;
  }
  
  @end
  </code></pre>