我正在尝试将整数转换为字符串,但遇到了问题。
我已经编写了大部分代码并且可以正常工作,但是在将其带到下一个地方时它有一个小缺陷。这很难描述,所以我给你举个例子。使用 base 26 和由小写字母组成的字符集:
0 = "一个"
1 = "b"
2 = "c"
...
25 = "z"
26 =“ba”(这应该等于“aa”)
在某些情况下似乎会跳过字符集中零处的字符。
让我感到困惑的是我看不出我的代码有什么问题。我已经研究这个太久了,但我还是想不通。
char* charset = (char*)"abcdefghijklmnopqrstuvwxyz";
int charsetLength = strlen(charset);
unsigned long long num = 5678; // Some random number, it doesn't matter
std::string key
do
{
unsigned int remainder = (num % charsetLength);
num /= charsetLength;
key.insert(key.begin(), charset[remainder]);
} while(num);
我感觉函数在返回零的模数上出错了,但我已经研究了这么久,我无法弄清楚它是怎么发生的。欢迎提出任何建议。
编辑:生成的字符串是小端字节序这一事实与我的应用程序无关。
最佳答案
如果我理解正确你想要什么(excel 对列使用的编号,A,B,.. Z,AA,AB,......)这是一个能够表示从 1 开始的数字的基本符号。 26数字的值为 1、2、... 26,基数为 26。因此 A 的值为 1,Z 的值为 26,AA 的值为 27...计算此表示非常类似于您只需要针对偏移量为 1 而不是 0。
#include <string>
#include <iostream>
#include <climits>
std::string base26(unsigned long v)
{
char const digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
size_t const base = sizeof(digits) - 1;
char result[sizeof(unsigned long)*CHAR_BIT + 1];
char* current = result + sizeof(result);
*--current = '\0';
while (v != 0) {
v--;
*--current = digits[v % base];
v /= base;
}
return current;
}
// for testing
#include <cstdlib>
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; ++i) {
unsigned long value = std::strtol(argv[i], 0, 0);
std::cout << value << " = " << base26(value) << '\n';
}
return 0;
}
运行 1 2 26 27 52 53 676 677 702 703 给出
1 = A
2 = B
26 = Z
27 = AA
52 = AZ
53 = BA
676 = YZ
677 = ZA
702 = ZZ
703 = AAA
关于c++ - 碱基转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2294443/