使用对数或其他方法从 C 中的任何基数转换为另一个基数

Using logarithms or other method to convert from any base to another base in C

我正在尝试编写一个 C 程序,将给定基数的数字转换为任何其他基数(例如,基数 2 二进制数转换为基数 8,或基数 3 转换为基数 16 十六进制)。我对此进行了相当多的研究,并且已经通读了一篇类似的文章,The math behind converting from any base to any base without going through base 10?] 但是在给出的解释中,他们使用了一个数组,而我不允许为这个程序这样做。

如果不为每个可能的基本转换组合编写一个方法的冗长程序,我不明白如果没有数组来存储可能的值,这是怎么可能的。我知道有一个带有日志的基本公式的变化允许我在数字基数之间改变,但我不清楚我将如何应用它,因为这个公式只给出一个十进制数答案,我仍然需要转换它。

int log_base_n(int n, int logof)
{
    double logBaseN = log10((double) logof) / log10((double) n);
    return (int) ceil(logBaseN);
}

这是我尝试将其用作中间步骤的二进制到十进制的转换:

/**
* Convert decimal numbers to binary. Uses a greedy subtraction
* algorithm. Assumes max integer allowed is 2 to 16 power.
*
* @param numberToConvert
*/
void decToBin(int numberToConvert)
{
int power = 16;
double ans = pow(2, power);

if (numberToConvert > ans)
{
    printf("ERROR: Number too large to convert!\n");
    return;
}

while (ans > numberToConvert)
{
    power--;
    ans = pow(2, power);
}

printf("%d", 0);

int i = power;

while (i >= 0)
{

    ans = pow(2, i);
    numberToConvert = numberToConvert - ans;
    printf("%d", 1);
    i--;

    while ((pow(2, i) > numberToConvert) && (i >= 0))
    {
        printf("%d", 0);
        i--;
        ans = pow(2, i);
    }
   }
}

我知道 Java 有一个 parseInt() 方法,可以进行基本转换,但是有没有类似的东西我可以用 C 实现,而不必像上面那样为每个可能的转换编写方法,同时仍然使用对数相关的想法?任何帮助将不胜感激。

but is there something similar I can implement in C without having to write methods for each possible conversion like the one above, while still utilizing a logarithm related idea?

对数是一个糟糕的选择。代码中日志的计算与其数学对应物不完全相同,导致输出不正确。

如果商导致的值略高于整数预期值,则下面是一个问题。当然,log10()logof <= 0的问题。

double logBaseN = log10((double) logof) / log10((double) n);
return (int) ceil(logBaseN);

另外,log_base_n()的计算完全没有必要。

这是一道整数题。使用整数数学。


一个简单的非数组解决方案"to convert from any base to another base"1就是使用递归

void print_int_base(int numberToConvert, int base) {
  // For now, assume numberToConvert >= 0, 2 <= base <= 36
  if (numberToConvert >= base) {
    print_int_base(numberToConvert/base, base);
  }
  int digit = numberToConvert%base;
  int c = digit < 10 ? digit + '0' : digit + 'A';
  putchar(c);
}

测试代码

#include <stdio.h>

void print_int_base_test(int numberToConvert, int base) {
  printf("%10d %2d:", numberToConvert, base);
  print_int_base(numberToConvert, base);
  puts("");
}

int main() {
  int numberToConvert = 42;
  for (int base=2; base<=20; base++) {
    print_int_base_test(numberToConvert, base);
  }
}

输出

42  2:101010
42  3:1120
42  4:222
42  5:132
42  6:110
42  7:60
42  8:52
42  9:46
42 10:42
42 11:39
42 12:36
42 13:33
42 14:30
42 15:2M
42 16:2K
42 17:28
42 18:26
42 19:24
42 20:22

1 OP 的转换想法显然是在各种基础上打印 int