Skip to content

Instantly share code, notes, and snippets.

@gleicon
Created March 26, 2012 14:44
Show Gist options
  • Select an option

  • Save gleicon/2205585 to your computer and use it in GitHub Desktop.

Select an option

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")
@gleicon
Copy link
Copy Markdown
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