简体   繁体   English

Javascript-字节数组要长吗?

[英]Javascript - byte array to long?

I have a byteArray constructed from Java, which contains longs . 我有一个从Java构造的byteArray ,其中包含longs I need to be able to read these longs in Javascript. 我需要能够使用Javascript阅读这些内容。 I understand that Javascript does not support longs by default. 我了解Javascript默认不支持longs Is there any way around this? 有没有办法解决? Can I read it as a String instead? 我可以改为将其读取为String吗?

Thanks 谢谢

The DataView.getInt64() implementation below will let you do it with enough precision: 下面的DataView.getInt64()实现将使您以足够的精度进行操作:

How to Read 64-bit Integer from an ArrayBuffer / DataView in JavaScript 如何从JavaScript中的ArrayBuffer / DataView读取64位整数

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. 我的Java服务器通过二进制websocket消息从System.currentTimeMillis()向所有客户端发送具有较长时间戳的玩家位置。 On client side to parse this message I am using DataView . 在客户端解析此消息时,我正在使用DataView

But DataView dont have method getInt64() . 但是DataView 没有方法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 . 而且这还节省了2个字节(长8个字节>整数4个字节+短2个字节),但是它将一直工作到2038年https://en.wikipedia.org/wiki/Year_2038_problem

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

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