0

I have a byteArray constructed from Java, which contains longs. I need to be able to read these longs in Javascript. I understand that Javascript does not support longs by default. Is there any way around this? Can I read it as a String instead?

Thanks

  • http://stackoverflow.com/questions/17320706/javascript-long-integer – Christophe Roussy Mar 14 '14 at 09:08
  • The real problem is that you won't be able to have numbers greater than 2^53 - 1 since JavaScript only knows about IEEE 754 64bit floating point numbers. But you can use bitwise operations to reconstruct as much as you can. You should also know whether the byte order is LE or BE, of course – fge Mar 14 '14 at 09:08
  • See my answer below, `currentTimeMilis()` will be < 2^53 – anthumchris Nov 01 '18 at 19:06

2 Answers2

0

I want to share my trick that may be useful for someone.

My java server sends for all clients positions of players with long timestamp from System.currentTimeMillis() via binary websocket message. On client side to parse this message I am using DataView.

But DataView dont have method getInt64(). And my solution was to send long in two pieces.

On server side:

long time = System.currentTimeMillis();
int firstPiece = (int)(time / 1000);
short secondPiece = (short)(time % 1000);

On client side:

let data = {};
let view = new DataView(binary);
data.t = view.getInt32(offset) * 1000 + view.getInt16(offset + 4);

And that also saves 2 bytes (long 8 bytes > int 4 bytes + short 2 bytes), but it will work until 2038 year https://en.wikipedia.org/wiki/Year_2038_problem.

7luc9ka
  • 28
  • 4
0

The DataView.getInt64() implementation below will let you do it with enough precision:

How to Read 64-bit Integer from an ArrayBuffer / DataView in JavaScript

anthumchris
  • 8,245
  • 2
  • 28
  • 53