All your Base62 are belong to us

I am currently working on my own url shortener: konv.es.  In order to create the shortest possible character hash of the url, I use the GetHashCode() method of the string, then convert the resulting number to base 62 ([0-9a-zA-Z]).  The most elegant solution that I have found thus far to make the convertion (which is also a handy-dandy example of a yield return) is:

private static IEnumerable<char> ToBase62(int number)
  {
    do
    {
      yield return "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[number % 62];
      number /= 62;

    } while (number > 0);
  }

Extra credit: re-factor as an extension method

Posted on November 22, 2011 at 8:59 pm by Steve Konves · Permalink
In: C#, konv.es

2 Responses

Subscribe to comments via RSS

  1. Written by Vlad
    on January 16, 2012 at 4:46 am
    Permalink

    Nice. One problem with this code though – negative numbers break it, getting an IndexOutOfRangeException!

  2. Written by Steve Konves
    on January 16, 2012 at 3:11 pm
    Permalink

    Thanks for the heads up. I originally had an input parameter of ‘uint’ to allow larger numbers to be passed in; however, that lead to some messy looking conversions because the the index used on the string (“0123…XYZ”) has to be an int.

    My to-do list for this one includes making able to accept ‘uint’ and ‘ulong’. Also, feel free to post any updated versions of this method :)

Subscribe to comments via RSS

Leave a Reply