Skip to content

Instantly share code, notes, and snippets.

@arnobaer
Last active July 5, 2018 16:00
Show Gist options
  • Save arnobaer/2e48cfec55351e9f34d2de6b806c76f6 to your computer and use it in GitHub Desktop.
Save arnobaer/2e48cfec55351e9f34d2de6b806c76f6 to your computer and use it in GitHub Desktop.
Base62 encoding in various languages
#ifndef base62_h
#define base62_h
#include <string>
/** Returns base 62 encoded unsigend integral value.
* base62(1234567890) // -> s"1ly7vk"
*/
std::string base62(unsigned long long value)
{
static const std::string alphabet{"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
static const std::size_t base = alphabet.size();
std::string result{};
while(value)
{
result.insert(0, alphabet.substr(value % base, 1));
value /= base;
}
return result.size() ? result : alphabet.substr(0, 1);
}
#endif
import string
def base62(value):
"""Returns base 62 encoded unsigend integral value.
>>> base62(1234567890)
'1ly7vk'
"""
value = abs(value) # unsigned!
alphabet = string.digits + string.letters
base = len(alphabet)
result = []
while value:
result.insert(0, alphabet[value % base])
value /= base
return ''.join(result) if result else alphabet[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment