我正在嘗試按照本教程 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 中沒有型別可以存盤如此大的數字怎么辦。
這個問題的最佳解決方案是什么?
uj5u.com熱心網友回復:
這個問題的最佳解決方案是什么?
檢查輸入有效性
如果字串是 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)。
選擇
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416398.html
標籤:
