什么是对通过JSON发送64位值的接受的方式?方式、JSON

2023-09-08 10:02:06 作者:扒衣见君节

我的一些数据是64位整数。我想送这些到一个页面上运行的JavaScript程序。

Some of my data are 64-bit integers. I would like to send these to a JavaScript program running on a page.

不过,据我所知道的,在大多数JavaScript实现整数为32位有符号的数量。

However, as far as I can tell, integers in most JavaScript implementations are 32-bit signed quantities.

我的两个选择似乎是:

将值作为字符串 发送的值作为64位浮点数

选项(1)不是完美的,但选择(2),似乎远不如完美(数据丢失)。

Option (1) isn't perfect, but option (2) seems far less perfect (loss of data).

你怎样处理这种情况呢?

How have you handled this situation?

推荐答案

这似乎是少了使用JSON和更多的问题与JavaScript本身的问题。什么是你打算如何处理这些数字呢?如果它只是你需要传递回网站以后,通过各种手段简单地使用包含值的字符串魔令牌。如果你确实有做算术的价值,你可能写你自己的JavaScript程序的64位运算。

This seems to be less a problem with JSON and more a problem with Javascript itself. What are you planning to do with these numbers? If it's just a magic token that you need to pass back to the website later on, by all means simply use a string containing the value. If you actually have to do arithmetic on the value, you could possibly write your own Javascript routines for 64-bit arithmetic.

这可以重新present值在Javascript(因此JSON)将是通过把数字成两个32位值的一种方法,例如

One way that you could represent values in Javascript (and hence JSON) would be by splitting the numbers into two 32-bit values, eg.

  [ 12345678, 12345678 ]

要拆分的64位值到2个32位的值,做这样的事情:

To split a 64-bit value into two 32-bit values, do something like this:

  output_values[0] = (input_value >> 32) & 0xffffffff;
  output_values[1] = input_value & 0xffffffff;

然后重新组合两个32位值,以一个64位的值:

Then to recombine two 32-bit values to a 64-bit value:

  input_value = ((int64_t) output_values[0]) << 32) | output_values[1];