2

我正在尝试按照本教程 https://learnmeabitcoin.com/technical/base58在 c 中制作 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 中没有类型可以存储如此大的数字怎么办。

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

4

1 回答 1

3

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

检查输入有效性

如果字符串是 BukQLKksdjkL7asSld = 11398419278238782..more

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

有效字符123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz


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

而不是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 位数字,代码需要使用一些类似这样的扩展数学,它使用字符串来确定斐波那契 (100)。

选择

于 2022-01-20T00:06:46.387 回答