Search code examples
javascripttype-conversionbignum

How do you convert big numbers from base6 to base16 in JavaScript?


How to convert a big number (120 digits) from base6 to base16 in JavaScript?

parseInt (JavaScript Function) has a problem with big numbers:

var big = 43535455245242542542542545353535345;
output1 = parseInt (big, 6);
output2 = output1.toString(16);
document.write (output2);

Even services like these do not work after 27 digits:

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-1.php https://www.unitconverters.net/numbers/base-6-to-base-16.htm

How can this be done in JavaScript?


Solution

  • In modern environments, you can use BigInt:

    // I assume your starting point is a string
    const big = "43535455245242542542542545353535345";
    // Parse in base 6
    const num = parseBigInt(big, 6);
    // Convert to base 16 via `toString`:
    const base16 = num.toString(16);
    console.log(base16);
    
    // There's no built-in parsing for base 6, so:
    function parseBigInt(str, base = 10) {
        if (typeof base !== "number" || isNaN(base) || base < 2 || base > 36) {
            throw new Error(`parseBigInt doesn't support base ${base}`);
        }
        let num = 0n;
        base = BigInt(base);
        for (const digit of str) {
            num *= base;
            num += BigInt(parseInt(digit, 6));
        }
        return num;
    }

    In older environments, you can use a polyfill or any of several "big number" libraries.

    Note: I didn't spend any time trying to make the above efficient. Just functional. :-)