Search code examples
javascriptbigint

Base 36 to 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)

Then I start losing precision.

Are there any methods for parsing directly into a BigInt?


Solution

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