base58编码和存储大数字?

base58 decoding & storing big numbers?

我正在按照本教程尝试用 c 语言制作一个 base58 解码器 https://learnmeabitcoin.com/technical/base58

To convert a base58 value in to base10,
you take each character index and multiply it with how many 58s that position in the number represents.

Then you just add all these values together.

base58 = BukQL

L = 19 * pow(58, 0) //= 19
Q = 23 * pow(58, 1) //= 1334
k = 43 * pow(58, 2) //= 144652
u = 52 * pow(58, 3) //= 10145824
B = 10 * pow(58, 4) //= 113164960

base10 = 19 + 1334 + 144652 + 10145824 + 113164960
base10 = 123456789

如您所见,仅需 5 个字符,数字就会变得相当大 BukQL = 113164960

如果字符串是BukQLKksdjkL7asSld = 11398419278238782..more怎么办 c 中没有类型可以存储如此大的数字。

这个问题的最佳解决方案是什么?

what is the best solution for this problem?

检查输入有效性

what if the string is BukQLKksdjkL7asSld = 11398419278238782..more

OP 的断言是错误的,因为 l 无效。

valid characters123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz


避免整数问题的浮动幂函数

而不是 pow(),只需在每次迭代时按 58 缩放即可。

对于最多 10 个 Base58 数字,代码可以使用各种 64 位类型。

const char base58[] =
    "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

uintmax_t base58_decode(const char *s) {
  printf("<%s>", s);
  uintmax_t val = 0;
  while (*s) {
    const char *pos = strchr(base58, *s);
    if (pos == NULL) {
      printf("\nInvalid <%c>\n", *s);
      exit -1;
    }
    val = val * 58 + (pos - base58);
    s++;
  }
  printf(" %ju\n", val);
  return val;
}

// Call examples
base58_decode("BukQL");
base58_decode("BukQLKksdjkL7asSld");  // Error out on 'l'

大数

要处理超过 10 位数字,代码需要使用一些扩展数学,例如 this,它使用字符串来确定 fibonacci(100)。

Alternative