Skip to content

Instantly share code, notes, and snippets.

@rorcraft
Created April 13, 2009 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rorcraft/94288 to your computer and use it in GitHub Desktop.
Save rorcraft/94288 to your computer and use it in GitHub Desktop.
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