Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

Then I start losing precision.

Are there any methods for parsing directly into a BigInt?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
734 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...