以36为底数的BigInt?

mpe*_*pen 6 javascript bigint

假设我想将base-36编码的字符串转换为BigInt,我可以这样做:

BigInt(parseInt(x,36))
Run Code Online (Sandbox Code Playgroud)

但是,如果我的字符串超过了可以安全地容纳在数字中的数字,该怎么办?例如

parseInt('zzzzzzzzzzzzz',36)
Run Code Online (Sandbox Code Playgroud)

然后我开始失去精度。

是否有任何直接解析为的方法BigInt

AKX*_*AKX 6

不确定是否有内置的,但是 base-X 到 BigInt 非常容易实现:

function parseBigInt(
  numberString,
  keyspace = "0123456789abcdefghijklmnopqrstuvwxyz",
) {
  let result = 0n;
  const keyspaceLength = BigInt(keyspace.length);
  for (let i = 0; i < numberString.length; 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"));
Run Code Online (Sandbox Code Playgroud)

输出

78364164095
78364164095n
29098125988731506183153025616435306561535n
Run Code Online (Sandbox Code Playgroud)

默认值与基数 36 使用的keyspace值相同parseInt,但如果您需要其他内容,可以使用该选项。:)


Nin*_*olz 5

您可以将数字转换为bigint类型。

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

console.log(convert('zzzzzzzzzzzzz', 36).toString());
Run Code Online (Sandbox Code Playgroud)

使用更大的块,例如仅十个(返回错误结果为11个)。

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());
Run Code Online (Sandbox Code Playgroud)