Skip to content

Instantly share code, notes, and snippets.

@gleicon
Created March 26, 2012 14:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gleicon/2205585 to your computer and use it in GitHub Desktop.
Save gleicon/2205585 to your computer and use it in GitHub Desktop.
base 62 encoding in ruby
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def base62_encode(num, alphabet=ALPHABET)
return alphabet[0] if num == 0
arr = []
base = alphabet.size
while num > 0 do
rem = num % base
num = num / base
arr << alphabet[rem]
end
arr.reverse
return arr.join
end
def base62_decode(string, alphabet=ALPHABET)
base = alphabet.size
strlen = string.size
num = 0
idx = 0
string.each_char do |char|
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
end
return num
end
puts base62_encode(128)
puts base62_decode("1F3")
@juanplopes
Copy link

Acho que esse código está errado:

Os testes abaixo não passam

base62_decode(base62_encode(128)).should == 128
base62_encode(base62_decode("1F3")).should == "1F3"

Fiz uma versão usando um approach mais funcional

https://gist.github.com/2209601

@gleicon
Copy link
Author

gleicon commented Mar 26, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment