Ad

JavaScript Convert Long Decimal To Hex And Back

- 1 answer

Prolog

I been experiencing something funny with JavaScript and I can't find why. I'm pretty sure its me and not the JavaScript.

Problem

When converting the integer number 72058145430680163 (18 digits) to hex, I obtain the hexadecimal representation 10000806191b260.

Although using the Dec2Hex converter RapidTables I get 10000806191b263. Latter is the correct number - 3 more then my result using Javascript.

Moreover, when converting my result back to int, it does return 72058145430680160 - 3 less then my original source integer.

Javascript used for conversion

Convert from dec to hex:

(72058145430680163).toString(16);

Convert from hex to dec (backwards):

parseInt((72058145430680163).toString(16), 16)

What am I doing wrong?

Ad

Answer

You are beyond the limits of JavaScript maximum. Use BigInt instead.

BigInt("72058145430680163").toString('16'); // Returns 10000806191b263 as String

And this does the whole round trip

BigInt("0x" + BigInt("72058145430680163").toString('16')).toString() // Retuns 72058145430680163

More information on BigInt here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Ad
source: stackoverflow.com
Ad