是否有 C 函数将以 X 为基数的数字字符串转换为以 Y 为基数的字符串?

Is there a C function to convert a string with a number in base X to a string in base Y?

我知道 strtol(hexstring, NULL, 16) 会将十六进制的字符串 hexstring 转换为十进制。同样,strtol(binstring, NULL, 2) 中的二进制就是这种情况。是否有一般情况下可以执行此操作的功能?从一个基地到另一个基地?如果没有,有人可以提出最高效的方法吗?

OP 都准备好知道如何将表示 base 数字的字符串 s 转换为整数。示例用法:

char *endptr;
errno = 0;
unsigned long y = strtoul(s, &endptr, base);
if (endptr == s) No_conversion();
if (errno) Handle_Overflow();
if (*endptr) Handle_TrailingText();

转换无符号整数的简单方法是使用 复合文字 进行内存分配。

How to use compound literals to fprintf() multiple formatted numbers with arbitrary bases?

如需其他方法,请搜索0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ

这是 C99 base_convert 的一个命题:

#include <stdlib.h>
#include <string.h>

static char *base_convert(const char * str, const int base_in, const int base_out) {
    static const char *alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    size_t a, b, c = 1, d;
    char *s = malloc(c + 1);
    strcpy(s, "0");
    for (; *str; ++str) {
        for (a = (char*)memchr(alphabet, *str, base_out) - alphabet, b = c; b;) {
            d = ((char *) memchr(alphabet, s[--b], base_out) - alphabet) * base_in + a;
            s[b] = alphabet[d % base_out];
            a = d / base_out;
        }
        for (; a; s = realloc(s, ++c + 1), memmove(s + 1, s, c), *s = alphabet[a % base_out], a /= base_out);
    }
    return s;
}

用法示例:

#include <stdio.h>

int main() {
    const char a[] = "10000000000000000000000000000000000000000000000000000000"
                     "00000000000000000000000000000000000000000000000000000000"
                     "00000000000000000000000000000000000000000000000000000000"
                     "00000000000000000000000000000000000000000000000000000000";
    char *b = base_convert(a, 2, 10);
    puts(b);
    free(b);
}

magic,示例输出:

13479973333575319897333507543509815336818572211270286240551805124608