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

3
  • stackoverflow.com/questions/17320706/javascript-long-integer Commented Mar 14, 2014 at 9: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 Commented Mar 14, 2014 at 9:08
  • See my answer below, currentTimeMilis() will be < 2^53 Commented Nov 1, 2018 at 19:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.