Created
March 26, 2012 14:44
-
-
Save gleicon/2205585 to your computer and use it in GitHub Desktop.
base 62 encoding in ruby
This file contains hidden or 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) | |
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") |
Author
gleicon
commented
Mar 26, 2012
via email
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