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") |
This comment has been minimized.
This comment has been minimized.
foi feito para não rodar testes.
fiz uma versao com monkey patch https://gist.github.com/2209621
puts i.to_base62.from_base62
puts c.from_base62.to_base62
1F3
4777
4777
1F3
##
More Cowbell
…On Monday, March 26, 2012 at 5:55 PM, Juan Lopes wrote:
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
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2205585
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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