I have developed a convertBase
function that is able to convert a value into different bases and back.
string convertBase(string value, int fBase, int tBase) {
string charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/",
fromRange = charset.substr(0, fBase),
toRange = charset.substr(0, tBase),
cc(value.rbegin(), value.rend()),
res = "";
unsigned long int dec = 0;
int index = 0;
for(char& digit : cc) {
if (charset.find(digit) == std::string::npos) return "";
dec += fromRange.find(digit) * pow(fBase, index);
index++;
}
while (dec > 0) {
res = toRange[dec % tBase] + res;
dec = (dec - (dec % tBase)) / tBase;
}; return res;
}
The code is working while encoding simple string like "Test"
and back again but gets it problems with encoding long strings like "Test1234567"
because it gets encoded as "33333333333333333333333333333333"
and that seems to be absolutely wrong!
Why is this happening and how to fix this issue?