Suppose I want to convert a base-36 encoded string to a BigInt
, I can do this:
BigInt(parseInt(x,36))
But what if my string exceeds what can safely fit in a Number? e.g.
parseInt('zzzzzzzzzzzzz',36)
Then I start losing precision.
Are there any methods for parsing directly into a BigInt
?
Base36 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-36 representation. The choice of 36 is convenient in that the digits can be represented using the Arabic numerals 0–9 and the Latin letters A–Z (the ISO basic Latin alphabet).
BigInt is a primitive wrapper object used to represent and manipulate primitive bigint values — which are too large to be represented by the number primitive.
Not sure if there's a built-in one, but base-X to BigInt is pretty easy to implement:
function parseBigInt(
numberString,
keyspace = "0123456789abcdefghijklmnopqrstuvwxyz",
) {
let result = 0n;
const keyspaceLength = BigInt(keyspace.length);
for (let i = numberString.length - 1; i >= 0; i--) {
const value = keyspace.indexOf(numberString[i]);
if (value === -1) throw new Error("invalid string");
result = result * keyspaceLength + BigInt(value);
}
return result;
}
console.log(parseInt("zzzzzzz", 36));
console.log(parseBigInt("zzzzzzz"));
console.log(parseBigInt("zzzzzzzzzzzzzzzzzzzzzzzzzz"));
outputs
78364164095
78364164095n
29098125988731506183153025616435306561535n
The default keyspace
there is equivalent to what parseInt
with base 36 uses, but should you need something else, the option's there. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With