Base 36 to BigInt?

后端 未结 2 1214
名媛妹妹
名媛妹妹 2020-12-06 12:32

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 ex

2条回答
  •  星月不相逢
    2020-12-06 12:52

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

提交回复
热议问题