Kevin
Kevin

Reputation: 23

JavaScript convert long decimal to hex and back

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?

Upvotes: 2

Views: 1814

Answers (2)

Daymon
Daymon

Reputation: 21

Your number is too large for Javascript. So what you're seeing occur is some overflow issues. What you can do to circumvent this is utilize the Javascript data-type BigInt.

So in practice, you could do something like this:

BigInt("72058145430680163").toString(16);

Upvotes: 2

Ctznkane525
Ctznkane525

Reputation: 7465

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

Upvotes: 5

Related Questions