Last active
August 18, 2021 14:03
-
-
Save heminy/1b189bf0db872639041f9bc0f31d012e to your computer and use it in GitHub Desktop.
base62 for C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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