Created
April 13, 2009 05:28
-
-
Save rorcraft/94288 to your computer and use it in GitHub Desktop.
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
class BaseCodec | |
def self.base_n_decode(s, alphabets) | |
n = alphabets.length | |
rv = pos = 0 | |
charlist = s.split("").reverse | |
charlist.each do |char| | |
rv += alphabets.index(char) * n ** pos | |
pos += 1 | |
end | |
return rv | |
end | |
def self.base_n_encode(num, alphabets) | |
n = alphabets.length | |
rv = "" | |
while num != 0 | |
rv = alphabets[num % n, 1] + rv | |
num /= n | |
end | |
return rv | |
end | |
end | |
class Base62 < BaseCodec | |
ALPHABETS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
def self.decode(s) | |
base_n_decode(s, ALPHABETS) | |
end | |
def self.encode(s) | |
base_n_encode(s, ALPHABETS) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment