I recently had a project where I wanted my web site content to utilize short URLs.  These short URL’s would be easier to utilize on Twitter where the message is limited to 140 characters.  At this stage link shortening is old news and I could use one of the many available link shortening services (Bit.ly, Goo.gl) to generate these links.  However, I dislike the idea of encouraging visitors to tweet a Bit.ly link, as opposed to my own links.
Using database ID’s to create short links
To address this my original idea was to simply rely on the auto-incremented row ID’s for each item in the database. Â For the database table, this looks something like this:
| ID | Title |
| 1 | Budgeting for your CMS or Web Project |
| 2 | How many web browsers support responsive design? |
| … | … |
| 95131 | Wanted: Video-conferencing solution for mid-sized teams |
Which means it would be easy to utilize shortened URL’s that look like this:
- http://mywebsite.com/1
- http://mywebsite.com/2
- http://mywebsite.com/95131
However, these URL’s aren’t as short as they could be. Â By only utilizing numbers (0-9) we’re not utilizing other valid characters (A-Z, a-z, -, _) that could potentially be used to create shorter URL’s.
Using Base 64 to create shorter URL’s
The numbers I’m utilizing for my database ID’s are using numbers based on 10.  Using this type of number I’m only utilizing the 0-9 characters  However, numbers that are based on 64 utilize other characters to represent numbers for which we do not have a character.
The way base 64 numbers are represented matches nicely with the characters that can be used in a URL. Â Therefore, by converting my base 10 database id’s into base 64 I’ll get a shorter URL. Â At the same time, I can be assured that the shortened URL’s aren’t duplicated since they are based on a unique database ID.
C# code for converting a Base-10 Integer to a Base-64 String
Ultimately, I wanted a solution that would work like this:
- ShortUrl.Shrink(95131) => Returns “XOb”
- ShortUrl.Expand(“XOb”) => Returns 95131
Here is the code I came up with.
Some notes
- The reason I didn’t use C#’s built-in Base-64 encoding is because it adds padding to the string. Â As a result, the Base-64 string often becomes longer than the original decimal number. Â (Making it useless for link shortening)
- There are decimal numbers that, when converted to Base-64, will turn into offensive words. Â I haven’t dealt with this yet.
- Someone else created a Base-10 to Base-64 converter with C#. Â It looks like this code uses bit-shifting. Â This is probably faster (and more clever), but I had trouble understanding the code.
- There is a nice website that you can use to test these conversions.
- That website is based on some PHP-code that can be found here.
