2

从以 12 为底转换到以 10 为底的最有效方法是什么,反之亦然?

我尝试了多种转换方法,例如转换为字符串,将每个字符分配为值,乘以base^exponent获取该基数中的值,然后得到总数。

我想知道,有没有更好的方法呢?

首先,我将数字存储为以十为底的字符串,并希望将其转换为以十二为底的另一个字符串。我还希望能够将该基数为 12 的数字(在字符串中)转换为基数为 10 的数字(在字符串中)。

4

1 回答 1

2

如果您只使用 base 2 作为中间体,这很容易。您可以将任何基数的字符串转换为基数 2,如下所示:

int x = strtol("12345", NULL, 10); // convert from base 10 string to integer
int y = strtol("12345", NULL, 12); // convert from base 12 string to integer

然后转换基数 10 是微不足道的:

sprintf(buf, "%d", y); // convert from integer to base 10 string

打印出以 12 为底的数字有点困难 - 没有内置函数可以做到这一点,因此您需要编写自己的(使用一些帮助程序保持清洁):

void reverse(char *s)                // reverse a string in place
{
    char *e = s + strlen(s) - 1;     // find the end of the string
    char tmp;
    while (s < e)                    // loop to swap characters and move pointers
    {                                // towards the middle of the string
        tmp = *e;
        *e-- = *s;
        *s++ = tmp;    
    }
}

char digit(int x)        // turn an integer into a single digit
{
    if (x < 10)
        return '0' + x;       // 0-9
    else
        return 'a' + x - 10;  // a, b, c, d, e, f, g....
}

void tobase(char *s, int x, int base) // convert an integer into a string in
{                                     // the given base
    int r;
    char *p = s;
    while (x)
    {
        r = x % base;    // extract current digit
        x = x / base;    // divide to get lined up for next digit
        *p++ = digit(r); // convert current digit to character
    }
    *p = '\0';           // null terminate the string
    reverse(s);          // and reverse it, since we generated the digits 
}                        // backwards

你会像这样使用它:

tobase(buf, x, 12); // convert from integer to base 12 string

您可能想要添加比我那里更好的错误处理 - 我正在拍摄一个简短的实现,以便在这里干净地安装它。

于 2013-01-05T00:00:10.833 回答