简体   繁体   English

如何在 JavaScript 中将十进制数转换为十六进制数?

[英]How to convert a decimal number in a hexadecimal number in JavaScript?

let me explain my problem.让我解释一下我的问题。 I used the following method to convert my binary number to decimal number: number.toString(16)我使用以下方法将二进制数转换为十进制数: number.toString(16)

This method renders a number that indeed appears to be in hexadecimal form.此方法呈现一个看起来确实是十六进制形式的数字。 But the problem is there: I need from the id of a user that I retrieve via an authentication API (steam in this case), and I need to retrieve data via a third-party SQL database.但问题就在那里:我需要通过身份验证 API(在本例中为蒸汽)检索的用户 ID,并且我需要通过第三方 SQL 数据库检索数据。 The identifier of this user on the database is indeed his steam identifier, but in hexadecimal form.这个用户在数据库中的标识符确实是他的蒸汽标识符,但是是十六进制的。

The problem is that the identifier that I retrieve and transform into hexadecimal form is not equal to that of the database.问题是我检索并转换为十六进制形式的标识符不等于数据库的标识符。 One could then wonder if the identifier of the database is not simply different?然后有人可能会想,数据库的标识符是否不只是不同? And that's where my various tests come in by proving me no!这就是我的各种测试通过证明我不来的地方!

Let me explain in more detail:让我更详细地解释一下:

With this code:使用此代码:

let n = 76561199121591748;
console.log(n.toString(16))

The code returns me:代码返回给我:

110000145386dc0

This should return me this (which is the database id):这应该返回给我这个(这是数据库 id):

110000145386dc4

According to all my tests (example of online scripts, test of nodejs conversion libraries etc) everything leads me to false results.根据我所有的测试(在线脚本示例、nodejs 转换库测试等),一切都导致我得出错误的结果。 Still, the online conversions sites (like this site ) show me the good result.尽管如此,在线转换网站(如 这个网站)向我展示了良好的结果。 So I imagine that the problem must come from the method.所以我想问题一定来自方法。 Can you tell me if there is an explanation for this?你能告诉我这是否有解释吗? Thanks in advance提前致谢

Javascript numbers are IEEE double-precision floats. Javascript 数字是 IEEE 双精度浮点数。 The set of integers that can be represented exactly are those integers n such that - 2 53 -1 <= n <= 2 53 -1.可以精确表示的整数集合是那些整数n ,使得 - 2 53 -1 <= n <= 2 53 -1。

The constant Number.MAX_SAFE_INTEGER has the value 2 53 -1, or 9,007,199,254,740,991 decimal.常数Number.MAX_SAFE_INTEGER的值为 2 53 -1,或十进制的 9,007,199,254,740,991。

Your value 76,561,199,121,591,748 is an order of magnitude larger than Number.MAX_SAFE_INTEGER and so can't be represented exactly.您的值76,561,199,121,591,748Number.MAX_SAFE_INTEGER大一个数量级,因此无法准确表示。

You might take a look at using BigInt instead of Number .您可以看看使用BigInt而不是Number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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