Created
July 31, 2014 15:08
-
-
Save dliv/b6e6901665b9f8d4740d to your computer and use it in GitHub Desktop.
Base36 Encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Minimize.Models.Utils | |
{ | |
public class Base36 | |
{ | |
private const string Base36CharSet = "0123456789abcdefghijklmnopqrstuvwxyz"; | |
public static string Encode(ulong raw) | |
{ | |
char[] base36Chars = Base36CharSet.ToCharArray(); | |
var result = new Stack<char>(); | |
while (raw != 0) | |
{ | |
result.Push(base36Chars[raw % 36]); | |
raw /= 36; | |
} | |
return new string(result.ToArray()); | |
} | |
public static ulong Decode(string encoded) | |
{ | |
ulong decoded = 0; | |
uint pos = 0; | |
foreach (var charSetIdx in encoded.ToLower().Reverse().Select(c => Base36CharSet.IndexOf(c))) | |
{ | |
if (charSetIdx < 0) | |
{ | |
throw new ArgumentOutOfRangeException("encoded", encoded, "Value to decode must be in base 36 (i.e. only contain characters \"" + Base36CharSet + "\"."); | |
} | |
decoded += (ulong)(charSetIdx * (int)Math.Pow(36, pos++)); | |
} | |
return decoded; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment