Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Forked from gleicon/base_62.rb
Created March 26, 2012 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanplopes/2209601 to your computer and use it in GitHub Desktop.
Save juanplopes/2209601 to your computer and use it in GitHub Desktop.
base 62 encoding in ruby (versão funcional)
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def base62_encode(num, alphabet=ALPHABET)
base = alphabet.size
char = ALPHABET[num%base,1]
return char if num < base
return char + base62_encode(num/base, alphabet)
end
def base62_decode(string, alphabet=ALPHABET)
base = alphabet.size
idx = alphabet.index(string[0..0])
return idx if string.size == 1
return idx + base62_decode(string[1..-1], alphabet) * base
end
puts base62_encode(0)
puts base62_decode("0")
puts base62_encode(128)
puts base62_decode("1F3")
puts base62_decode(base62_encode(128))
puts base62_encode(base62_decode("1F3"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment