I am trying to make a base58 decoder in c following this tutorial 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
as you see the number can bee quite big fast only with 5 characters BukQL = 113164960
what if the string is BukQLKksdjkL7asSld = 11398419278238782..more
there is no type in c who can store such very large numbers.
what is the best solution for this problem?
what is the best solution for this problem?
Check for input validity
what if the string is BukQLKksdjkL7asSld = 11398419278238782..more
OP's assertion is in error as l
is invalid.
The valid characters are 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz
Avoid floating power functions for an integer problem
Rather than pow()
, simply scale by 58 on each iteration.
For up to 10 Base58 digits, code can use various 64-bit types.
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'
Big numbers
To handle more that 10 digits, code needs to employ some extended math like this that uses a string to determine fibonacci(100).