This might be a duplicate of Convert byte array to numbers in JavaScript but the best answer there is quite old (maybe there is something new?) and I would also like to approach this in an open ended manner and ask a broader question regarding if there is a better way to send data in a performant way instead of what I am trying to do.
I am currently working on making a real time game using webrtc run by a C# server.
For updating the client I am currently playing around with this code converting numbers to a byte[]
which I can then send to the client (to minimize the data, this turns into 50 bytes). This is important as I'll be sending several updates per second.
public static byte[] UserLocationToByte(long userId, double x, double y, double r, double dx, double dy)
{
var msg = new List<byte[]>
{
BitConverter.GetBytes((short)DataMessageType.Location),
BitConverter.GetBytes(userId),
BitConverter.GetBytes(x),
BitConverter.GetBytes(y),
BitConverter.GetBytes(r),
BitConverter.GetBytes(dx),
BitConverter.GetBytes(dy)
};
var t = msg.SelectMany(a => a).ToArray();
return t;
}
In C# I could convert this back to the number values using.
// convert it back.
var rtype = (DataMessageType)BitConverter.ToInt16(bytes, 0);
var ruserId = BitConverter.ToInt64(bytes, 2);
var rx = BitConverter.ToDouble(bytes, 2 + 8);
var ry = BitConverter.ToDouble(bytes, 2 + 8 + 8);
var rr = BitConverter.ToDouble(bytes, 2 + 8 + 8 + 8);
var rdx = BitConverter.ToDouble(bytes, 2 + 8 + 8 + 8 + 8);
var rdy = BitConverter.ToDouble(bytes, 2 + 8 + 8 + 8 + 8 + 8);
Searching around I found no simple way to do this in javascript/typescript.
I could just send strings with | separators and parse those in javascript, but that would increase the amount of data by quite alot.
Any suggestions as to how to either parse a byte[] in javascript or another way to approach this problem all together?
I have no problem just supporting firefox and chrome.