Skip to content

Instantly share code, notes, and snippets.

@heminy
Last active August 18, 2021 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heminy/1b189bf0db872639041f9bc0f31d012e to your computer and use it in GitHub Desktop.
Save heminy/1b189bf0db872639041f9bc0f31d012e to your computer and use it in GitHub Desktop.
base62 for C++
#include <iostream>
#include <cassert>
using namespace std;
const string CODES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string toBase62(int value) {
string str;
do {
str.insert(0, string(1, CODES[value % 62]));
value /= 62;
} while (value > 0);
return str;
}
int toBase10(string value) {
std::reverse(value.begin(), value.end());
int ret = 0;
int count = 1;
for (char& character : value) {
ret += CODES.find(character) * count;
count *= 62;
}
return ret;
}
int main() {
assert("3bj" == toBase62(12233));
assert(12233 == toBase10("3bj"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment