Skip to content

Instantly share code, notes, and snippets.

@mxcl
Created February 6, 2010 16:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxcl/296792 to your computer and use it in GitHub Desktop.
Save mxcl/296792 to your computer and use it in GitHub Desktop.
Readable Base 62 encoder
# 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