Created
February 6, 2010 16:17
-
-
Save mxcl/296792 to your computer and use it in GitHub Desktop.
Readable Base 62 encoder
This file contains hidden or 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
# Use this for your URL shortening needs | |
# Base 62 is as good as you can easily get for URL shortening | |
# And it's effective: 1_000_000 => '4c92' | |
# Challenge: fork and speed up the implementation! | |
class Fixnum | |
TOKENS = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a | |
# NOTE returns nil for 0 | |
def to_62_s | |
i = self | |
s = '' | |
while i > 0 | |
s << TOKENS[i.modulo(62)] | |
i /= 62 | |
end | |
s.reverse | |
end | |
def self.base62(s) | |
i = 0 | |
n = 1 | |
s.reverse.each_byte do |c| | |
i += TOKENS.index(c.chr) * n | |
n *= 62 | |
end | |
return i | |
end | |
end | |
if __FILE__ == $0 | |
s = 1_000_000.to_62_s | |
assert Fixnum.base62(s) == 1_000_000 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment