【发布时间】:2018-03-31 17:36:21
【问题描述】:
我开发了一个convertBase 函数,它能够将值转换为不同的基数并返回。
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;
}
代码在编码像"Test" 这样的简单字符串并再次返回时工作,但是在编码像"Test1234567" 这样的长字符串时遇到问题,因为它被编码为"33333333333333333333333333333333",这似乎是绝对错误的!
为什么会发生这种情况以及如何解决这个问题?
【问题讨论】:
-
首先,如果您使用 C++ 编程,请不要添加任何不相关的语言标签。其次,这是learn how to debug your programs的最佳时机。
-
fBase、tBase有哪些值?unsigned long是否足够大以供您计算? (我希望:没有)。您使用的是pow的哪个重载 - 没有声明在 cplusplus.com/reference/cmath/pow 处返回整数类型 -
好吧听起来合法,但有什么替代方法可以代替“unsigned long”? @milbrandt
-
您可能会使用一些大型 int 库,如 stackoverflow.com/questions/1055661/bigint-bigbit-library 中引用的。你的算法是否适用于
long doubleprecisssion? -
取模不是问题。
a % b = a - floor(a/b)*b也适用于十进制类型。
标签: c++ arrays string math base