-
-
Save juanplopes/2209601 to your computer and use it in GitHub Desktop.
base 62 encoding in ruby (versão funcional)
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
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