Skip to content

Instantly share code, notes, and snippets.

@gabesumner
Created March 21, 2012 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gabesumner/2148657 to your computer and use it in GitHub Desktop.
Save gabesumner/2148657 to your computer and use it in GitHub Desktop.
Provides a short URL slug based on the database row ID. This is done by converting a (Base10) Int into a (Base64) String
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace MvcApplication.Helpers
{
public static class ShortUrl
{
/// <summary>
/// Converts a Base-10 Integer to Base-64. This will effectively shorten the number of characters used to represent a number > 10.
/// </summary>
public static string Shrink(int Number)
{
return ConvertDecToBase(Number, 64);
}
/// <summary>
/// Converts a Base-64 Number (represented as a string) into a Base-10 Integer. This will effectively expand the numbers of characters needed to represent the number.
/// </summary>
/// <param name="NumberString"></param>
/// <returns></returns>
public static int Expand(string NumberString)
{
return ConvertBaseToDec(NumberString, 64);
}
private static string DefaultChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static string Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
private static int ConvertBaseToDec(string NumberString, int Base)
{
string Chars;
if (Base == 64)
{
NumberString = Regex.Replace(NumberString, "^A+", "");
Chars = Base64Chars;
}
else
{
NumberString = Regex.Replace(NumberString, "^0+", "");
Chars = DefaultChars;
}
int Dec = 0;
for (int i = 0; i <= NumberString.Length - 1; i++)
{
int CharNum = Chars.IndexOf(NumberString[i]);
int Conversion = CharNum * IntPow(Base, (NumberString.Length - (i + 1)));
Dec = Dec + Conversion;
}
return Dec;
}
private static string ConvertDecToBase(int OriginalNumber, int Base)
{
char[] Chars;
if (Base == 64)
{
Chars = Base64Chars.ToCharArray();
}
else
{
Chars = DefaultChars.ToCharArray();
}
string encoded = "";
encoded = ConvertDecToBase(OriginalNumber, Base, encoded, Chars);
return encoded;
}
private static string ConvertDecToBase(int Number, int Base, string EncodedString, char[] Chars)
{
if (Number < Base)
{
EncodedString = EncodedString + Chars[Number];
}
else
{
int NewNumber = Number / Base;
EncodedString = ConvertDecToBase(NewNumber, Base, EncodedString, Chars);
Number = Number - (NewNumber * Base);
if (Number < Base)
{
EncodedString = EncodedString + Chars[Number];
}
}
return EncodedString;
}
private static int IntPow(int x, int pow)
{
int ret = 1;
while (pow != 0)
{
if ((pow & 1) == 1)
ret *= x;
x *= x;
pow >>= 1;
}
return ret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment