以36为底数的BigInt? [英] Base 36 to BigInt?

查看:40
本文介绍了以36为底数的BigInt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想将base-36编码的字符串转换为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)

然后我开始失去精度.

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

Are there any methods for parsing directly into a BigInt?

推荐答案

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

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

这篇关于以36为底数的BigInt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆