将 36 进制转为 BigInt?

Base 36 to BigInt?

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

BigInt(parseInt(x,36))

但是如果我的字符串超出了 safely fit in a Number 的范围怎么办?例如

parseInt('zzzzzzzzzzzzz',36)

然后我开始失去精度。

有没有直接解析成BigInt的方法?

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

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"));

产出

78364164095
78364164095n
29098125988731506183153025616435306561535n

默认的 keyspace 相当于 parseInt 以 36 为基数使用的值,但是如果您需要其他东西,可以使用该选项。 :)

您可以将数字转换为 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());

更大的块,例如十个(十一 return 错误结果)。

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());