Base 36 to BigInt?

后端 未结 2 1206
名媛妹妹
名媛妹妹 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. :)

    0 讨论(0)
  • 2020-12-06 12:57

    You could convert the number to a bigint type.

    function convert(value, radix) {
        return [...value.toString()]
            .reduce((r, v) => r * BigInt(radix) + BigInt(parseInt(v, radix)), 0n);
    }
    
    console.log(convert('zzzzzzzzzzzzz', 36).toString());

    With greater chunks, like just for example with ten (eleven return a false result).

    function convert(value, radix) { // value: string
        var size = 10,
            factor = BigInt(radix ** size),
            i = value.length % size || size,
            parts = [value.slice(0, i)];
    
        while (i < value.length) parts.push(value.slice(i, i += size));
    
        return parts.reduce((r, v) => r * factor + BigInt(parseInt(v, radix)), 0n);
    }
    
    console.log(convert('zzzzzzzzzzzzz', 36).toString());

    0 讨论(0)
提交回复
热议问题