Convert to Base 62 in Cocoa

Published on — Filed under protip, cocoade

A quick and easy way to generate a random password in Cocoa is to generate a random number using arc4random() and then convert that number into its Base 62 representation.

According to Google, converting to Base 62 doesn't seem to be very common in objc, so here's a handy piece of code, straight from DroplrKit — converts an unsigned long number in decimal base (radix 10) to string a representing that same number in base 62.

const char kDKFunctionsBase62Alphabet[62] =
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

NSString* DKBase62Encode(unsigned long long number) {
  if (number == 0) return @"0";

  NSMutableString* result = [[NSMutableString alloc] init];
  while (number > 0) {
    NSUInteger remainder = number % 62;
    char remainderChar = kDKFunctionsBase62Alphabet[remainder];
    NSString* toInsert = [NSString stringWithFormat:@"%c", remainderChar];
    [result insertString:toInsert atIndex:0];
    number = (number - remainder) / 62;
  }

  return result;
}

Algorithm should hold for any other alphabet you want to use, provided you adjust the divisor and alphabet constants.

Also, beware of the alphabet used. I tend to like the order 0-9A-Za-z — just like in the ASCII table — but I've seen other variations.