c - 如何将数字字符串存储为任意大整数?

标签 c math digits arbitrary-precision

ib 为输入基数,ob 为输出基数。 str 是一些任意大整数 x 的 ASCII 表示。我需要定义 f,例如:

f(str="1234567890", ib=10, ob=16) = {4, 9, 9, 6, 0, 2, 13, 2}

... 其中 f 的返回类型是一个包含此整数的基本 int 数字的 ob 数组。我们假设 2 >= ob <= MAX_INT2 >= ib <= 10 以及 str 将始终是一个有效的字符串(不需要否定)。

最佳答案

一些东西可以让 OP 开始,但足以让 OP 享受编码体验。

// form  (*d) = (*d)*a + b
static void mult_add(int *d, size_t *width, int ob, int a, int b) {
    // set b as the carry
    // for *width elements,
    //   x = (Multiply d[] by `a` (using wider than int math) and add carry)
    //   d[] = x mod ob
    //   carry = x/ob
    // while (carry <> 0)
    //   widen d
    //   x =  carry
    //   d[] = x mod ob
    //   carry = x/ob
}

int *ql_f(const char *src, int ib, int ob) {
  // Validate input
  assert(ib >= 2 && ib <= 10);
  assert(ob >= 2 && ob <= INT_MAX);
  assert(src);

  // Allocate space
  size_t length = strlen(src);
  // + 2 + 4 is overkill, OP to validate and right-size later
  size_t dsize = (size_t) (log(ib)/log(ob)*length + 2 + 4);   
  int *d = malloc(sizeof *d * dsize);
  assert(d);

  // Initialize d to zero
  d[0] = 0;
  size_t width = 1;
  while (*src) {
    mult_add(d, &width, ob, ib, *src - '0');
    src++;
  }

  // add -1 to end, TBD code

  return d;
}

关于c - 如何将数字字符串存储为任意大整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39600970/

相关文章:

javascript - 在数字/数字和字母/字符之间添加空格

javascript - 使用draw2d在JavaScript中围绕主圆绘制圆

algorithm - 括号对的递归算法

python - 将任意长度的列表或元组传递给用 C 编写的 Python 扩展

c - 将内存分配给指向指针变量的指针时出现段错误 [C]

algorithm - 大数除法余数

Java 十六进制到十进制转换 : Custom Logic

algorithm - 给定一个数字系列,找到校验位算法......?

c++ - 我的容器类中应该允许多少整数?

c - 具有作用域和全局变量的 Malloc