首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >base58解码&存储大数字?

base58解码&存储大数字?
EN

Stack Overflow用户
提问于 2022-01-19 21:24:24
回答 1查看 318关注 0票数 0

我正试图在c++中制作一个base58解码器,遵循本教程https://learnmeabitcoin.com/technical/base58

代码语言:javascript
复制
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中没有一个类型可以存储这么大的数字。

解决这个问题的最好办法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-20 00:06:46

解决这个问题的最好办法是什么?

检查输入有效性

如果字符串是BukQLKksdjkL7asSld = 11398419278238782..more怎么办?

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

有效字符123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz

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

而不是pow(),只需在每次迭代中扩展58次。

对于多达10 Base58的数字,代码可以使用各种64位类型.

代码语言:javascript
复制
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位数字,代码需要使用一些扩展的数学方法,比如,它使用字符串来确定fibonacci(100)。

替代方案

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70777930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档