簡體   English   中英

如何將數字字符串存儲為任意大整數?

[英]How to store a digit string into an arbitrary large integer?

ib為輸入基准,而ob為輸出基准。 str是任意大整數x的ASCII表示形式。 我需要定義f如:

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

...,其中f的返回類型是一個int數組,其中包含此整數的基數ob digits。 我們假設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;
}

我用較舊的規范編寫了此代碼,因此它不再有效,但作為起點可能會有用。

該代碼可以處理long long 在C語言中使用任意精度的數字是一個巨大的飛躍!

請注意,使用-1作為結束標記而不是0 可以接受2到36之間的ib和任何ob

包括示例main

函數f 不能按原樣重入。 為了使其具有線程安全性,它可以分配所需的內存,然后返回指向它的指針。 最簡單的協議是讓調用者隨后負責釋放內存。

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>

int *f(const char *str, int ib, int ob) {
    static int result[CHAR_BIT * sizeof(long long) + 1];
    int i = sizeof(result) / sizeof(int) - 1;
    long long l = strtoll(str, NULL, ib);
    result[i--] = -1;
    while (l) {
        result[i] = l % ob;
        l /= ob;
        i--;
    }
    return result + i + 1;
}

int main()
{
    int *x = f("1234567890", 16, 10);
    while (*x > -1) {
        printf("%d ", *x);
        x++;
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM