【发布时间】:2018-04-03 09:06:59
【问题描述】:
我想开发一种能够在 C++ 中进行 AnyBase 2 AnyBase 转换的算法。
所以我开始只是将this javascript code 翻译成 C++,最后使用了BigInt - library,因为它当然不能使用整数(long int、long 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;
}
我希望有人能够帮助我找到我的错误,因为我自己似乎无法找到它。
在此先感谢一百万,Tempi。
【问题讨论】:
-
为什么要调用
operator函数而不是使用运算符? -
例如,
BigInt::Rossi newDec = (decValue - decValue % base) / base;比您的函数调用序列和字符串转换更具可读性。如果你不把事情弄得那么复杂,那么发现错误会容易得多。 -
@molbdnilo 好点,是的。尽管如此,这似乎并没有改变代码的“不工作”。太糟糕了。
-
所以代码
(C++)是我从 JavaScript 代码翻译而来的,你可以在这里 find right。我通过使用 bigInt 而不是仅具有 53 位精度的 Int 改进了 javascript 代码(就像 javascript 一样)。希望我能回答你的评论:) @Teemu -
JS 仍然与问题完全无关......无论我写了多少 JS 行作为答案,它都无助于解决手头的 C++ 问题。
标签: c++ string type-conversion integer base