C++将int转换为具有未知基的字符串的简单方法

C++ easy way to convert int to string with unknown base

本文关键字:字符串 简单 方法 未知 int 转换 C++      更新时间:2023-10-16

以下是Java中的代码:

int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);

现在我想在C++中也一样,但我找到的所有转换都只转换为基数10。我不想用mysleft实现这一点,为什么要写一些已经存在的

尽管std::strtol更灵活,但在受控情况下,您也可以使用itoa

int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);

如果想要基数为8或16,则可以轻松使用字符串操纵器std::octstd::hex。如果你想要任意基数,我建议你看看这个问题。

无错误处理http://ideone.com/nCj2XG:

char *toString(unsigned int value, unsigned int radix)
{
    char digit[] = "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ";
    char stack[32];
    static char out[33];
    int quot, rem;
    int digits = 0;
    do
    {
        quot = value / radix;
        rem = value % radix;
        stack[digits] = digit[rem];
        value = quot;
        digits++;
    }
    while( value );
    int i = 0;
    while(digits--)
    {
        out[i++] = stack[digits];
    }
    out[i] = 0;
    return out;
}

没有标准函数itoa,它可以执行到任意微积分系统的转换。但例如,在我的编译器版本中没有实现。我的解决方案:

#include <string>
// maximum radix - base36
std::string int2string(unsigned int value, unsigned int radix) {
    const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    while (value > 0) {
        unsigned int remainder = value % radix;
        value /= radix;
        result.insert(result.begin(), base36[remainder]);
    }
    return result;
}