Search code examples
javascriptnode.jsstringhex

Converting a number to hex string causes error in JS


let val = dcd["value"];
console.log(val)

result:

67874000000000000n

Converting val to a hex string causes error:

let val_hex = val.toString('hex');

RangeError: toString() radix argument must be between 2 and 36
    at BigInt.toString (<anonymous>)

Solution

  • The toString() method is used to convert a number to a string in a given radix (base), where the radix can be any number between 2 and 36. In order to convert a number to hex string, use base 16.

    const bigIntNumber = 67874000000000000n;
    const hexNumber = bigIntNumber.toString(16);
    console.log(hexNumber); // "f2fada63a00000"