Skip to content

Instantly share code, notes, and snippets.

@guilleiguaran
Last active August 29, 2015 14:12
Show Gist options
  • Save guilleiguaran/2e0f799484b49f1b536d to your computer and use it in GitHub Desktop.
Save guilleiguaran/2e0f799484b49f1b536d to your computer and use it in GitHub Desktop.
class Base62
BASE62_ALPHABET = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
def encode(str)
packed_int = str.unpack('C*').each_with_index.reduce(0){|r,(x,i)| r + (x << 8*i) }
return '0' if packed_int == 0
s = ''
while packed_int > 0
s << BASE62_ALPHABET[packed_int.modulo(62)]
packed_int /= 62
end
s.reverse
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment