Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.