简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM