我想开发一种能够在C++中完成 AnyBase 2 AnyBase转换的算法。

因此,我首先只是将this javascript code转换为C++,最后使用BigInt - library,因为使用整数(长整数,长 double 等)精度当然不起作用-因此,我不得不使用BigInt库。

这是我想出的代码。到现在为止,我还没有收到错误消息或警告,但是转换似乎没有完成它的工作:

string enc1 = convertBaseBigInt("A", 64, 4);
cout << "enc1: " << enc1 << endl;               // gets "210000"

string dec1 = convertBaseBigInt(enc1, 4, 64);   // gets "2g0" (instead of "A")
cout << "dec1: " << dec1 << endl;

请看一下我的代码:
std::string convertBase(string value, int from_base, int to_base) {
string range = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/";
string  from_range = range.substr(0, from_base),
        to_range = range.substr(0, to_base);

int dec_value = 0;
int index = 0;
string reversed(value.rbegin(), value.rend());
for(std::string::iterator it = reversed.begin(); it != reversed.end(); ++it) {
    index++;
    char digit = *it;
    if (!range.find(digit)) return "error";
    dec_value += from_range.find(digit) * pow(from_base, index);
}
string new_value = "";
while (dec_value > 0) {
    new_value = to_range[dec_value % to_base] + new_value;
    dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value;
}

我希望有人能够帮助我找到我的错误,因为似乎我自己找不到它。

提前感谢一百万,坦皮。

最佳答案

我认为您的问题是您没有使用正确的“索引”值,它应从0开始而不是1

去掉

index++

并修改线
BigInt::Rossi add(to_string((int)(from_range.find(digit)
 * pow(from_base, index))), BigInt::DEC_DIGIT);


BigInt::Rossi add(to_string((int)(from_range.find(digit)
 * pow(from_base, index++))), BigInt::DEC_DIGIT);

我还建议删除operator关键字

例如
decValue.operator>(BigInt::Rossi("0", BigInt::DEC_DIGIT))

当这更清楚
decValue > BigInt::Rossi("0", BigInt::DEC_DIGIT)

10-01 03:57
查看更多