jak*_*gut 2 c++ base itoa modulo
我现在正在尝试将整数转换为字符串,但遇到了问题。
我已经完成了大部分代码的编写和工作,但是在传送到下一个地方时它有一个小缺陷。这很难描述,所以我给你举个例子。使用 base 26 和由小写字母组成的字符集:
0 = "a"
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);
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,该函数在返回零的模数上绊倒了,但我一直在研究这个,我无法弄清楚它是如何发生的。欢迎任何建议。
编辑:生成的字符串是小端的这一事实与我的应用程序无关。
如果我正确理解您想要什么(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;
}
Run Code Online (Sandbox Code Playgroud)
运行 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
Run Code Online (Sandbox Code Playgroud)