Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@juanplopes juanplopes commented Mar 26, 2012

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

This comment has been minimized.

Copy link
Owner Author

@gleicon gleicon commented Mar 26, 2012

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.