Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base 36 to BigInt?

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?

like image 851
mpen Avatar asked Apr 12 '19 07:04

mpen


People also ask

What is base 36 called?

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).

What is BigInt?

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.


1 Answers

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. :)

like image 92
AKX Avatar answered Sep 27 '22 16:09

AKX