Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the accepted way to send 64-bit values over JSON?

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

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

My two options seem to be:

  1. Send the values as strings
  2. Send the values as 64-bit floating point numbers

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

How have you handled this situation?

like image 933
Frank Krueger Avatar asked Oct 16 '08 19:10

Frank Krueger


People also ask

Does JSON support 64-bit integers?

> JSON doesn't have 64-bit integers. The JSON "number" type has no limitations on the range. All 64-bit integers, both signed and unsigned, can be encoded as JSON numbers.

How big is too big for a JSON response?

One of the more frequently asked questions about the native JSON data type, is what size can a JSON document be. The short answer is that the maximum size is 1GB.

How many digits is a 64-bit integer?

As a recap, remember that the maximum number stored in a 64 bit register / variable is 2^64 – 1 = 18446744073709551615 (a 20 digit number).

Does JSON support long?

As a practical matter, Javascript integers are limited to about 2^53 (there are no integers; just IEEE floats). But the JSON spec is quite clear that JSON numbers are unlimited size.


1 Answers

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.

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 ] 

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; 

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

  input_value = ((int64_t) output_values[0]) << 32) | output_values[1]; 
like image 57
Simon Howard Avatar answered Oct 12 '22 03:10

Simon Howard